Dmitriy Tkachenko
Dmitriy Tkachenko

Reputation: 324

Method call with assignment syntax

Recently I have encountered the following code:

var l = List("a")
l :+= "b"

The second line, quite intuitively (similar to += increment), gets compiled to a method call and assignment:

l = l :+ "b"

As I can see, it is not limited to library classes. For example, this compiles:

trait CustomList[+A] {
  def :+[B >: A](item: B): CustomList[B]
}

var a: CustomList[String] = ...
a :+= "a"

But it is obviously limited to only symbolic method names:

trait CustomList[+A] {
  def add[B >: A](item: B): CustomList[B]
}

var a: CustomList[String] = ...
a add= "a"

This fails to compile (let's just ignore the fact that it looks bad), although it looks the same.

I could not find the documentation for this feature. So the question is, what is this syntax called? And what are the precise rules (regarding naming, method's arity, etc.) as to which method calls in the form of <variable> <method-name>= <args> get rewritten as <variable> = <variable> <method-name> <args>?

Upvotes: 1

Views: 94

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

It's a Scala feature called Assignment Operators.

Here's the reference you're looking for (Scala language spec v2.11, chapter 6, section 12, paragraph 4)

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:

  • the operator also starts with an equals character, or
  • 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 +.

Upvotes: 1

Related Questions