Skip to content

Instantly share code, notes, and snippets.

@mucaho
Last active August 29, 2015 14:15
Show Gist options
  • Save mucaho/49f785ce26af70e5c1e1 to your computer and use it in GitHub Desktop.
Save mucaho/49f785ce26af70e5c1e1 to your computer and use it in GitHub Desktop.
Scala polymorphic type filtering
object FilterTypes extends App {
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._
object RichClass {
def unapply[T](a: RichClass[T]): Option[T] = Option(a.value)
}
implicit class RichClass[T](val value: T)(implicit val classTag: ClassTag[T], val typeTag: TypeTag[T]) {}
def getOfType[T : ClassTag : TypeTag](list: Seq[RichClass[_]]): Seq[T] = {
list.collect {
case richClass @ RichClass(elem: T) if richClass.typeTag.tpe =:= typeOf[T] => elem
}
}
val anyLists : Seq[RichClass[_]] = Seq(
List("A", "B"), List("C"),
List(1), List(2,3),
List(true, false)
)
val stringLists : Seq[List[String]] = getOfType[List[String]](anyLists)
println(stringLists.mkString(" "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment