考虑Array[Any]
val a = Array(1,2,"a")
a: Array[Any] = Array(1, 2, a)
我们可以像这样收集Int
类型的所有项目,
a.collect { case v: Int => v }
res: Array[Int] = Array(1, 2)
虽然如何定义一个收集给定类型项目的函数,但未成功尝试过这个,
def co[T](a: Array[Any]) = a.collect { case v: T => v }
warning: abstract type pattern T is unchecked since it is eliminated by erasure
提供
co[Int](a)
ArraySeq(1, 2, a)
co[String](a)
ArraySeq(1, 2, a)
答案 0 :(得分:7)
您需要为模式匹配提供ClassTag
才能实际运作:
import scala.reflect.ClassTag
def co[T: ClassTag](a: Array[Any]) = a.collect { case v: T => v }