简体   繁体   English

Scala中的+ =运算符

[英]+= operator in Scala

I'm reading Programming in Scala by M. Odersky and now I'm trying to understand the meaning of operators. 我正在阅读M. Odersky的Scala编程,现在我正在努力理解运算符的含义。 As far as I can see, any operator in Scala is just a method. 据我所知,Scala中的任何运算符都只是一种方法。 Consider the following example: 请考虑以下示例:

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);
}

I this case we have only + operator defined in this class. 在这种情况下,我们在这个类中只定义了+运算符。 And if we type something like this: 如果我们键入这样的东西:

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

then 然后

=+
30

will be the output. 将是输出。 So I'd assume that for each class (or type?) in Scala we have += operator defined for it, as a += b iff a = a + b . 所以我假设对于Scala中的每个类(或类型?),我们为它定义了+=运算符,因为a += b iff a = a + b But since every operator is just a method, where the += operator defined? 但是因为每个运算符只是一个方法,其中+ =运算符定义了? Maybe there is some class (like Object in Java) containing all the defenitions for such operators and so forth. 也许有一些类(如Java中的Object )包含这些运算符的所有defenition等等。

I looked at AnyRef in hoping to find, but couldn't. 我看着AnyRef希望找到,但不能。

+= and similar operators are desugared by the compiler in case there is a + defined and no += is defined. +=和类似的运算符被编译器去掉,以防有+定义且没有定义+= (Similarly works for other operators too.) Check the Scala Language Specification ( 6.12.4 ): (同样适用于其他运营商。)检查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. 让我们在中缀操作l + = r中考虑赋值运算符,例如+ =,其中l,r是表达式。 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. l = l + r,但操作的左侧l仅被评估一次。

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 +=. 左侧l没有名为+ =的成员,也无法通过隐式转换转换为名为+ =的成员的值。 The assignment l = l + r is type-correct. 赋值l = l + r是类型正确的。 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 +. 特别地,这意味着l指的是可以分配给的变量或对象,并且可以转换为具有名为+的成员的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM