Is it possible to write an \"asInstanceOfOption\" method that would do what is intended by the following (bogus) code?
def asInstanceOfOption[T](o: Any): Option[
Here's an elaboration on oxbow_lake's updated answer, further updated to require Scala 2.10:
// Implicit value class
implicit class Castable(val obj: AnyRef) extends AnyVal {
def asInstanceOfOpt[T <: AnyRef : ClassTag] = {
obj match {
case t: T => Some(t)
case _ => None
}
}
}
This can be used by doing:
"Hello".asInstanceOfOpt[String] == Some("Hello") // true
"foo".asInstanceOfOpt[List[_]] == None // true
However as mentioned in other answers this doesn't work for primitives because of boxing issues, nor does it handle generics because of erasure. To disallow primitives, I restricted obj
and T
to extend AnyRef
. For a solution that handles primitives, refer to the answer for Matt R's followup question:
How to write asInstanceOfOpt[T] where T <: Any
Or use shapeless's Typeable, which handles primitives as well as many erasure cases:
Type casting using type parameter