The following code can be compiled without errors.
val a: Int = 1
val b = a.asInstanceOf[AnyRef]
That makes me confused, because Int extends AnyVal which is not a subclass but a sibling of AnyRef.
However, if an ascription is used as following:
val a: Int = 1
val b: AnyRef = a
It doesn't work.
error: type mismatch;
found : Int
required: AnyRef
Note: an implicit exists from scala.Int => java.lang.Integer, but
methods inherited from Object are rendered ambiguous. This is to avoid
a blanket implicit which would convert any scala.Int to any AnyRef.
You may wish to use a type ascription: `x: java.lang.Integer`.
val b: AnyRef = a
What I am understanding :
asInstanceOf
is executed at run time, it forces compiler to believe val a is an AnyRef.
However, an ascription is at compile time, the conversion can not pass the type check, so we have a "type mismatch" error.
My questions:
- Basically, why does the conversion work at run time ?
- If AnyRef is considered as java.lang.Object in JVM, how about AnyVal ? Is it an Object at run time ?
- (If yes, what's its type ? java.lang.Object ? But AnyVal is sibling of AnyRef, isn't it ?)
- (If not, how can we use some AnyVal's subclass as Object, like Int, Double)
- Are there some tricks played by scala compiler ?