且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 scalac 需要在需要“Any"的方法中装箱“Int"

更新时间:2022-06-20 21:40:58

Any 可以在 Scala 中在语法上使用,因为编译器自动装箱任何 Java 原始类型(这就是 Intcode> 相当于) 根据需要.从发出的字节码中,您可以看到 INVOKEVIRTUAL 在具有以下签名的方法上被调用:

Any can be syntactically used in Scala since the compiler auto boxes any Java primitive type (which is what Int is equivalent to) as needed. From the emitted byte code, you see that INVOKEVIRTUAL is called on a method with the following signature:

scala/Predef$.println (Ljava/lang/Object;)V

由于Java中没有Any的概念,scalac发出Object的方法签名,在Scala中相当于AnyRef.由于Int 扩展了AnyVal,我们需要分配等效的Java 包装器,即Integer.

Since there is no notion of Any in Java, scalac emits method signature of Object, which in Scala is equivalent to AnyRef. Since Int extends AnyVal, we need to allocate the equivalent Java wrapper, which is Integer.