可以编译以下代码,而不会出现错误。
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是AnyRef。然而,一个归属是在编译时,转换不能通过类型检查,所以我们有一个“类型错配”错误。
我的问题:
发布于 2014-09-19 12:01:10
这是因为自动装箱:
scala>val a: Int = 1
a: Int = 1
scala> a.getClass
res2: Class[Int] = int
scala> val b = a.asInstanceOf[AnyRef]
b: AnyRef = 1
scala> b.getClass
res1: Class[_ <: AnyRef] = class java.lang.Integer通过强制转换为AnyRef (java.lang.Object),您将触发从int到java.lang.Integer的自动装箱
如果AnyRef在JVM中被认为是
java.lang.Object,那么AnyVal如何?在运行时它是一个对象吗?
AnyRef确实是一个别名,因为java.lang.Object AnyVal是一个“虚拟”类型,它只存在于编译时,是为了类型系统的完整性。
在运行时,扩展AnyVal的实例被转换为相应的本机类型(int、double等),但String除外,后者本身扩展了java.lang.Object,但在JVM中有特殊的处理。
但
AnyVal是AnyRef的兄弟姐妹,不是吗?)
AnyVal和AnyRef都扩展了Any类型,但它们并不相互扩展。
scala编译器有什么花招吗?
负载:)
要更完整地解释Scala类型的等级,我建议您先阅读:http://docs.scala-lang.org/tutorials/tour/unified-types.html
发布于 2014-09-19 15:59:29
作为“自动拳击”的补充,您可以观察到使用了什么魔法。
-Xprint:all将展示哪个编译器阶段发挥了神奇的作用。
-Ytyper-debug显示了typer所做的决定。
例如,给定val a: Int,则val b = a.isInstanceOf[AnyRef]在擦除中更改为Int.box(a).$asInstanceOf[Object],其中$asInstanceOf是Object的名义成员。
关于这些转换,擦除有一个很好的注释
/** Replace member references as follows:
*
* - `x == y` for == in class Any becomes `x equals y` with equals in class Object.
* - `x != y` for != in class Any becomes `!(x equals y)` with equals in class Object.
* - x.asInstanceOf[T] becomes x.$asInstanceOf[T]
* - x.isInstanceOf[T] becomes x.$isInstanceOf[T]
* - x.isInstanceOf[ErasedValueType(tref)] becomes x.isInstanceOf[tref.sym.tpe]
* - x.m where m is some other member of Any becomes x.m where m is a member of class Object.
* - x.m where x has unboxed value type T and m is not a directly translated member of T becomes T.box(x).m
* - x.m where x is a reference type and m is a directly translated member of value type T becomes x.TValue().m
* - All forms of x.m where x is a boxed type and m is a member of an unboxed class become
* x.m where m is the corresponding member of the boxed class.
*/相反,由于OP的错误消息中提到的归属而进行的转换是由于Predef中的隐式
scala> val I: java.lang.Integer = a
[[syntax trees at end of typer]] // <console>
private[this] val I: Integer = scala.this.Predef.int2Integer($line3.$read.$iw.$iw.a);https://stackoverflow.com/questions/25931611
复制相似问题