Method call with assignment syntax

一笑奈何 提交于 2020-01-15 09:13:00

问题


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>?


回答1:


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


来源:https://stackoverflow.com/questions/38190606/method-call-with-assignment-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!