+= operator in Scala

11,732

+= 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):

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 +.

Share:
11,732
stella
Author by

stella

Updated on August 15, 2022

Comments

  • stella
    stella over 1 year

    I'm reading Programming in Scala by M. Odersky and now I'm trying to understand the meaning of operators. As far as I can see, any operator in Scala is just a method. 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. 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.

    I looked at AnyRef in hoping to find, but couldn't.