Accepted answer

x ++= y appears to have the same behavior as x = x ++ y

It does.

but I cannot find where this behavior is coming form.

It's built into the language. When x op= y can't be interpreted as a calling the method op= (because no such method exists in x's class or any class that it can be implicitly converted to), it's instead interpreted as calling the method op and an assignment.

(and where is it documented?)

In Scala's language specification, section 6.12.4:

Assignment Operators

An assignment operator is an operator symbol (syntax category op in Identifiers) that ends in an equals character “=”, with the exception of operators for which one of the following conditions holds:

  1. the operator also starts with an equals character, or
  2. the operator is one of (<=), (>=), (!=).

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.

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

Related Query

More Query from same tag