我正在尝试根据类型动态过滤(或收集)列表:
如果我这样做明确指定类型,它工作正常
scala> var aList = List("one", 2, 3.3)
aList: List[Any] = List(one, 2, 3.3)
scala> aList.collect{case x:Int => x}
res10: List[Int] = List(2)
Run Code Online (Sandbox Code Playgroud)
如果我想编写一个方法来执行此操作,那么它不会:
scala> def collectType[T](l:List[Any]):List[T] = l.collect{case x:T => x}
warning: there were unchecked warnings; re-run with -unchecked for details
collectType: [T](l: List[Any])List[T]
scala> collectType[Int](aList)
res11: List[Int] = List(one, 2, 3.3)
scala> collectType[Double](aList)
res16: List[Double] = List(one, 2, 3.3)
scala> collectType[String](aList)
res14: List[String] = List(one, 2, 3.3)
Run Code Online (Sandbox Code Playgroud)
我一开始以为它是在命名"Integer"类型而不是使用Integer作为类型,但似乎并非如此:
collectType[Int](aList).foreach(x => println(x))
java.lang.ClassCastException: java.lang.String cannot be cast to …Run Code Online (Sandbox Code Playgroud)