gpt4 book ai didi

scala - Scala 中的 += 运算符

转载 作者:行者123 更新时间:2023-12-03 04:22:03 24 4
gpt4 key购买 nike

我正在阅读 M. Odersky 所著的《Scala 编程》,现在我正在尝试理解运算符的含义。据我所知,Scala 中的任何运算符都只是一种方法。考虑以下示例:

class OperatorTest(var a : Int) {

def +(ot: OperatorTest): OperatorTest = {
val retVal = OperatorTest(0);
retVal.a = a + ot.a;
println("=")
return retVal;
}
}

object OperatorTest {
def apply(a: Int) = new OperatorTest(a);
}

在这种情况下,我们在此类中仅定义了 + 运算符。如果我们输入这样的内容:

var ot = OperatorTest(10);
var ot2 = OperatorTest(20);
ot += ot2;
println(ot.a);

然后

=+
30

将是输出。所以我假设对于 Scala 中的每个类(或类型?),我们都为其定义了 += 运算符,如 a += b iff a = a + b 。但由于每个运算符都只是一个方法,那么 += 运算符在哪里定义呢?也许有一些类(如 Java 中的 Object)包含此类运算符等的所有定义。

我查看了 AnyRef 希望能找到,但找不到。

最佳答案

如果定义了 + 而没有定义 +=,则编译器会对

+= 和类似运算符进行脱糖处理。 (对于其他运算符也同样有效。)检查 Scala 语言规范 ( 6.12.4 ):

Assignment operators are treated specially in that they can be expanded to assignments if no other interpretation is valid.

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.

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 +=. 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 中的 += 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039905/

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