I was trying to answer this question, as I thought I knew the answer. Turns out, I did not know quite enough :/
Here is a test I have done:
class In
While @0__'s answer explains why it doesn't work, here is how to make it work:
class Inst[T](implicit tag: scala.reflect.ClassTag[T]) {
def is(x: Any) = tag.runtimeClass.isInstance(x)
// scala.util.Try { as(x) }.isSuccess will work as well
def as(x: Any): T = tag.runtimeClass.cast(x).asInstanceOf[T]
}
object Main extends App {
println(new Inst[String].is(3))
println(new Inst[String].as(3))
}
false
java.lang.ClassCastException: Cannot cast java.lang.Integer to java.lang.String
at java.lang.Class.cast(Class.java:3369)
...