Scala - 迭代一个包含 List() 的 Any 变量
Scala - Iterate a Any variable which contains List()
scala >
var a : Any = List(1,2,3,4,5,6,7,8,9,0)
我想迭代变量a。因为它打印
1
2
3
4
5
6
7
8
9
0
只需使用模式匹配:
a match {
case l: List[Int] => l.foreach(println)
}
P.S.: 正如@IvanStanislavciuc 巧妙地注意到的那样,有一个警告:
warning: non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure
1
因为类型擦除,但是List
需要一个类型参数,所以你也可以传递Any
而不是Int
。
诸如List
的集合通常"iterated"使用map/foreach
高阶方法,但是我们不能直接在a
上调用它们的原因是因为编译器认为a
的类型是 Any
,因为我们明确指定了类型注释 a: Any
。
var a: Any = List(1,2,3,4,5,6,7,8,9,0)
| |
compile-time type runtime class
Any
不提供 map/foreach
API 所以我们能做的最好的就是执行引用 a
到 class List[_]
像这样
if (a.isInstanceOf[List[_]]) a.asInstanceOf[List[_]].foreach(println) else ???
可以使用模式匹配等价地加糖
a match {
case value: List[_] => value.foreach(println)
case _ => ???
}
作为旁注,由于 type erasure 我们只能检查 "top-level" class List
而不是,例如, List[Int]
,因此 a.isInstanceOf[List[Int]]
有点误导,所以我更喜欢表达它 a.isInstanceOf[List[_]]
。
scala >
var a : Any = List(1,2,3,4,5,6,7,8,9,0)
我想迭代变量a。因为它打印
1
2
3
4
5
6
7
8
9
0
只需使用模式匹配:
a match {
case l: List[Int] => l.foreach(println)
}
P.S.: 正如@IvanStanislavciuc 巧妙地注意到的那样,有一个警告:
warning: non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure 1
因为类型擦除,但是List
需要一个类型参数,所以你也可以传递Any
而不是Int
。
诸如List
的集合通常"iterated"使用map/foreach
高阶方法,但是我们不能直接在a
上调用它们的原因是因为编译器认为a
的类型是 Any
,因为我们明确指定了类型注释 a: Any
。
var a: Any = List(1,2,3,4,5,6,7,8,9,0)
| |
compile-time type runtime class
Any
不提供 map/foreach
API 所以我们能做的最好的就是执行引用 a
到 class List[_]
像这样
if (a.isInstanceOf[List[_]]) a.asInstanceOf[List[_]].foreach(println) else ???
可以使用模式匹配等价地加糖
a match {
case value: List[_] => value.foreach(println)
case _ => ???
}
作为旁注,由于 type erasure 我们只能检查 "top-level" class List
而不是,例如, List[Int]
,因此 a.isInstanceOf[List[Int]]
有点误导,所以我更喜欢表达它 a.isInstanceOf[List[_]]
。