Here's the contrived experiments in REPL (scala 2.11):
scala> class Foo[T] {
| def as(x: Any) = x.asInstanceOf[T]
| }
defined class Foo
scala> val foo = new Foo[String]
foo: Foo[String] = Foo@65ae6ba4
scala> val x: Any = 123
x: Any = 123
scala> foo.as(x) // expected
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
... 33 elided
scala> val y: Any = "abc"
y: Any = abc
scala> foo.as(y)
res1: String = abc
scala> class Bar[T] {
| def is(x: Any) = x.isInstanceOf[T]
| }
<console>:12: warning: abstract type T is unchecked since it is eliminated by erasure
def is(x: Any) = x.isInstanceOf[T]
^
defined class Bar
scala> val bar = new Bar[String]
foo: Foo[String] = Foo@1753acfe
scala> val x: Any = 123
x: Any = 123
scala> bar.is(x) // unexpected
res2: Boolean = true
scala> val y: Any = "abc"
y: Any = abc
scala> bar.is(y)
res3: Boolean = true
I know type parameter is quite limited due to type erasion, but still confused by the different behaviours between asInstanceOf and isInstanceOf here.
Wonder if someone has any insight about that? Thanks!