Consider an Array[Any]
val a = Array(1,2,"a")
a: Array[Any] = Array(1, 2, a)
We can collect all the items of type Int
like this,
a.collect { case v: Int => v }
res: Array[Int] = Array(1, 2)
Though how to define a function that collects items of a given type, having unsuccessfully tried this,
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
which delivers
co[Int](a)
ArraySeq(1, 2, a)
co[String](a)
ArraySeq(1, 2, a)
You need to provide a ClassTag
for the pattern match to actually work:
import scala.reflect.ClassTag
def co[T: ClassTag](a: Array[Any]) = a.collect { case v: T => v }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With