Skip to content

Instantly share code, notes, and snippets.

@luciferous
Created May 5, 2015 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciferous/8037bb0395d7e5c02725 to your computer and use it in GitHub Desktop.
Save luciferous/8037bb0395d7e5c02725 to your computer and use it in GitHub Desktop.
sealed trait Value
sealed trait Prim[A] extends Value {
def value: A
}
case class StringPrim(value: String) extends Prim[String]
val x: Value = StringPrim("hi")
def get[A](v: Value): Option[A] = v match {
case p: Prim[A] => Some(p.value)
case _ => None
}
// scala> get[String](x)
// res0: Option[String] = Some(hi)
// scala> get[Int](x)
// res1: Option[Int] = Some(hi)
def get2[A](v: Value)(implicit tag: scala.reflect.ClassTag[A]): Option[A] = v match {
case p: Prim[A] if p.value.getClass == tag.runtimeClass => Some(p.value)
case _ => None
}
// scala> get2[String](x)
// res0: Option[String] = Some(hi)
// scala> get2[Int](x)
// res1: Option[Int] = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment