Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala collect items of a type from a collection

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)
like image 626
elm Avatar asked Dec 10 '14 12:12

elm


1 Answers

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  }
like image 146
gzm0 Avatar answered Sep 18 '22 17:09

gzm0