Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused by the operator definitions of Int in Scala

Tags:

scala

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")
like image 631
zjffdu Avatar asked Jan 07 '12 05:01

zjffdu


2 Answers

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.

like image 103
sbridges Avatar answered Nov 14 '22 18:11

sbridges


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.

like image 28
Esko Luontola Avatar answered Nov 14 '22 20:11

Esko Luontola