I am trying to achieve to write a method that casts a value of Any to a specific type and returns option instead of throwing an exception like instanceOf. Scala does not behave like i have expected it:
def cast[A](value: Any): Option[A] =
{
try
{
Some(value.asInstanceOf[A])
} catch
{
case e: Exception => None
}
}
The test:
val stringOption: Option[String] = cast[String](2)
stringOption must beNone
fails with the Error
java.lang.Exception: 'Some(2)' is not None
Somebody has an idea why?
Erasure rains on your parade here. Therefore at runtime the type A is not known anymore and
asInstanceOf[A]is compiled to a no-op. It just makes the compiler believe that the resulting value is of type A, but that is not actually ensured at runtime.You can use Scala’s manifests to work around it, though. Unfortunately the JVM’s handling of primitive types / boxing forces us to do some extra work.
The following works, although it doesn’t handle “weak conformance” of types, meaning that e.g. an Int is not considered a Long, so
cast[Long](42)returnsNone.