In following code, a
is declared as AnyRef
but its type check for type String
is also true. Does Scala compiler convert the type of an object at runtime?
scala> val a:AnyRef = "hello"
a: AnyRef = hello
scala> a.isInstanceOf[String]
res6: Boolean = true
scala> a.isInstanceOf[Any]
res8: Boolean = true
scala> a.isInstanceOf[AnyRef]
res9: Boolean = true
scala> a.isInstanceOf[Object]
res12: Boolean = true
There are two different concepts involved: static (compile-time) type and runtime type. By declaring
val a: AnyRef
you only affect its static type, but at runtime its value is"hello"
and so the runtime type isString
.isInstanceOf
tests the runtime type.The compiler is not "assessing the value and treating
a
as aString
"; the JVM is.