Does scala compiler converts the type of an object dynamically (at run time)

54 views Asked by At

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
1

There are 1 answers

0
Alexey Romanov On BEST ANSWER

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 is String. isInstanceOf tests the runtime type.

The compiler is not "assessing the value and treating a as a String"; the JVM is.