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: AnyRefyou only affect its static type, but at runtime its value is"hello"and so the runtime type isString.isInstanceOftests the runtime type.The compiler is not "assessing the value and treating
aas aString"; the JVM is.