The scala tutorial says that Int
's add operation is actually a method call: 1+1
means 1.+(1)
But when I look into the source code of Int.scala
, it appears that the method will simply print an error message. Could anyone explain to me how this works?
def +(x: Int): Int = sys.error("stub")
Int is a value class, which is somewhat different than other classes. There is no way to express primitive addition in scala without getting into a recursive definition. For example if the definition of + was,
def +(x: Int): Int = this + x
Then calling + would invoke + which would invoke + which ...
Scala needs to compile the methods on value classes into the java byte codes for addition/subtraction/etc.
The compiler does compile + into the java bytecode for addition, but the scala library authors wrote Int.scala with stub methods to make it a valid scala source file. Those stub methods are never actually invoked.
As the implementation says, that method is a stub. Apparently its implementation is provided by the Scala compiler when the code is compiled, because int + int
is a primitive operation and the Scala language does not itself have primitives - only the compiler knows about primitives on the JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With