Last active
August 29, 2015 14:15
-
-
Save mucaho/49f785ce26af70e5c1e1 to your computer and use it in GitHub Desktop.
Scala polymorphic type filtering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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