Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+= operator in Scala

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.

like image 636
stella Avatar asked Jun 26 '16 15:06

stella


People also ask

What are the 7 types of operators?

The value that the operator operates on is called the operand. In Python, there are seven different types of operators: arithmetic operators, assignment operators, comparison operators, logical operators, identity operators, membership operators, and boolean operators.

What does >> mean in Scala?

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.


1 Answers

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

like image 140
Gábor Bakos Avatar answered Sep 27 '22 18:09

Gábor Bakos