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 beh
This is because of type erasure. At runtime, A
in Option[A]
is not known, so you are permitted to store a Some(3)
in a variable of type Option[String]
.
The exception will occur when the value inside the option is accessed:
scala> val result = cast[String](2)
result: Option[String] = Some(2)
scala> result.get
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at .(:10)
at .()
// ...