gpt4 book ai didi

scala - Scala 中 int 的 += 方法在哪里

转载 作者:行者123 更新时间:2023-12-01 07:53:37 24 4
gpt4 key购买 nike

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

例如,

var x=5
x+=1

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

我做不到,
5+=1

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

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

最佳答案

没有+=方法,扩展为 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 +.

关于scala - Scala 中 int 的 += 方法在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36937807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com