Search code examples
scalagenericspartialfunction

Scala : Collect with generics


Given the following scenario

val items = List("a", "b", "c", 1, 2, 3, false, true)
def intItems = items.collect {case i : Int => i}
def stringItems = items.collect {case s : String => s}

is there a way to create a generic function to handle this behavior?

I tried the following

def itemsAs[T]: List[T] = items.collect { case item: T => item } 

but

itemsAs[Int] 

returns

List[Int]] = List(a, b, c, 1, 2, 3, false, true)

Another approach is to provide the partial function as argument, but still have to duplicate the case i: Int => i and case s: String => s. Is there a way to make it more compact? Thanks


Solution

  • val items = List("a", "b", "c", 1, 2, 3, false, true)
    import scala.reflect.ClassTag
    def collect[T: ClassTag] = items.collect { case x: T => x }
    collect[Int] // List(1, 2, 3)
    collect[String] // List(a, b, c)
    

    See http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html for more details.