I'd like to cast variables dynamically to Option[T]
. The semantic is: if variable x
matches T
type, then cast should return Some(x)
and it should return None
otherwise. Using single map invocation is much cleaner than using isInstanceOf[T]
accompanying asInstanceOf[T]
or building monstrous case switches.
I had tried simple code below
object OptionCast {
def apply[T](source : Any) : Option[T] = source match {
case s : T => Some(s)
case _ => None
}
}
but it ignores types actually: OptionCast[Int]("some").map(_ + 2)
gives me type error.
How should I rewrite this code?
The problem with your code is that
T
is erased -- methods in bytecode do not have type parameters, soT
is erased toObject
and, therefore, true for everything.This works, with some limitations:
There are two important limitations here:
OptionCast.apply[List[Int]](List("a"))
and it will returnSome(List("a"))
. To get around that, you have to get around type erasure.AnyVal
class will be boxed, so you have to check againstjava.lang.Integer
to catchInt
, and so on.