Why should a scalar embed `Int` in a method expecting` Any`

Consider the following class:

package test
class Test {
  def main(args: Array[String]): Unit = {
    val i: Int = 0
    println(i)
  }
}

Bytecode main:

public main([Ljava/lang/String;)V
   // parameter final  args
  L0
   LINENUMBER 4 L0
   ICONST_0
  L1
   ISTORE 2
  L2
   LINENUMBER 5 L2
   GETSTATIC scala/Predef$.MODULE$ : Lscala/Predef$;
   ILOAD 2
   INVOKESTATIC scala/runtime/BoxesRunTime.boxToInteger (I)Ljava/lang/Integer;
   INVOKEVIRTUAL scala/Predef$.println (Ljava/lang/Object;)V
  L3
   RETURN
  L4
   LOCALVARIABLE i I L1 L3 2
   LOCALVARIABLE this Ltest/Test; L0 L4 0
   LOCALVARIABLE args [Ljava/lang/String; L0 L4 1
   MAXSTACK = 2
   MAXLOCALS = 3

As you can see, when we call println, Intgets the box in java.lang.Integer. But the signature println:

def println(x: Any): Unit

How Int <: AnyVal <: Any, why do I need to Intinsert into a box in a call?

+4
source share
1 answer

AnyIt can be syntactically used in Scala, since any primitive Java type is automatically placed at the compiler (which is equivalent Int). From the emitted byte code, you see what INVOKEVIRTUALis called by the method with the following signature:

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

Java Any, scalac Object, Scala AnyRef. Int extends AnyVal, Java, Integer.

+2

Source: https://habr.com/ru/post/1688823/


All Articles