zjffdu
zjffdu

Reputation: 28764

Confused by the operator definitions of Int in 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")

Upvotes: 20

Views: 546

Answers (3)

sbridges
sbridges

Reputation: 25140

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.

Upvotes: 25

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

It is important to realize that operators are methods as a matter of how one interacts with the language. Things like + on Int act like any other method in Scala, instead of being something that plays by their own rules.

However, at the implementation level, they are not methods at all: to the JVM only classes have methods, and the AnyVal subclasses are not classes as far as the JVM is concerned. Unsurprisingly, at the implementation level they act mostly like Java primitives.

Upvotes: 7

Esko Luontola
Esko Luontola

Reputation: 73625

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.

Upvotes: 7

Related Questions