Scala collect items from the collection

Consider Array[Any]

 val a = Array(1,2,"a") a: Array[Any] = Array(1, 2, a) 

We can collect all elements of type Int as follows:

 a.collect { case v: Int => v } res: Array[Int] = Array(1, 2) 

Although how to define a function that collects elements of a certain type, unsuccessfully trying 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 provides

 co[Int](a) ArraySeq(1, 2, a) co[String](a) ArraySeq(1, 2, a) 
+5
source share
1 answer

You need to provide a ClassTag to match the pattern:

 import scala.reflect.ClassTag def co[T: ClassTag](a: Array[Any]) = a.collect { case v: T => v } 
+7
source

Source: https://habr.com/ru/post/1208730/


All Articles