Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a += b become a = a + b in Scala?

Scala only sometimes desugars

a += b

to

a = a + b

but not always. For example, some mutable collections define a += method, where instead it becomes

a.+=(b)

Is this behaviour

  1. entirely determined by whether there is a suitable += method on a? (incl. are there any other examples of this behaviour?)
  2. independent of whether the objects are val or var?

Relevant example

Adapted from Programming in Scala, in

var s = Set("a", "b")
s += "c"

In this case, the second line of code s += "c" is essentially shorthand for:

s = s + "c"
like image 954
joel Avatar asked Aug 21 '18 15:08

joel


1 Answers

When does a += b become a = a + b in Scala?

When there is no applicable += method, there is an applicable + method and a is assignable (that is, it's a var or there's an a_= method).

Or as the spec puts it:

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

Is this behaviour

  1. entirely determined by whether there is a suitable += method on a?
  2. independent of whether the objects are val or var?

Not quite. If there is a suitable += method, it will be called regardless of any other factors (such as a being assignable). But when there isn't, the other factors determine whether it's desugared or you get an error message.

Note that the error message you get is different than the one you'd get from the desugared version: When the criteria for the desugaring don't apply, you get an error message that tells you "+= is not a member of ...", plus an explanation why the desugaring couldn't be applied (such as "receiver is not assignable" or the type error you'd get from a + b if a + b would produce a type error).

like image 161
sepp2k Avatar answered Sep 22 '22 09:09

sepp2k