Created
May 5, 2015 21:35
-
-
Save luciferous/8037bb0395d7e5c02725 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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