Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 475
Bruno Avatar asked Nov 26 '25 23:11

Bruno


1 Answers

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.

like image 150
dveim Avatar answered Nov 29 '25 15:11

dveim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!