scala中int的+=方法在哪里

Where is += method located for int in scala

在 Scala 中,+=(或任何赋值运算符)是 Int 类型的方法。

例如,

var x=5
x+=1

这里只有当它是一个变量时我才能使用+=方法

我做不到,

5+=1

scala 编译器是否将此方法视为特例?

为什么在 scala.Int class 中不可用?

没有+=方法,编译器扩展为x = x + 1。这在 specification:

中有详细说明

6.12.4 赋值运算符

Let's consider an assignment operator such as += in an infix operation l += r, where l, r

are expressions. This operation can be re-interpreted as an operation which corresponds to the assignment

l = l + r

except that the operation's left-hand-side l is evaluated only once.

The re-interpretation occurs if the following two conditions are fulfilled.

  1. The left-hand-side l does not have a member named +=, and also cannot be converted by an implicit conversion to a value with a member named +=.

  2. The assignment l = l + r is type-correct. In particular this implies that l refers to a variable or object that can be assigned to, and that is convertible to a value with a member named +.