【发布时间】:2014-11-13 21:53:44
【问题描述】:
以下代码可以正常编译。
val a: Int = 1
val b = a.asInstanceOf[AnyRef]
这让我很困惑,因为 Int 扩展了 AnyVal,它不是 AnyRef 的子类而是兄弟。
但是,如果按以下方式使用归属:
val a: Int = 1
val b: AnyRef = a
它不起作用。
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
我的理解:
asInstanceOf 在运行时执行,它强制编译器相信 val a 是 AnyRef。
但是,由于在编译时,转换无法通过类型检查,所以出现“类型不匹配”错误。
我的问题:
- 基本上,为什么转换在运行时起作用?
- 如果 AnyRef 在 JVM 中被视为 java.lang.Object,那么 AnyVal 呢?它是运行时的对象吗?
- (如果是,它的类型是什么?java.lang.Object ?但是 AnyVal 是 AnyRef 的兄弟,不是吗?)
- (如果没有,我们如何使用一些AnyVal的子类作为Object,比如Int、Double)
- scala 编译器有什么技巧吗?
【问题讨论】:
标签: scala