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
+=
method on a
? (incl. are there any other examples of this behaviour?)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"
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.
- 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 thatl
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
- entirely determined by whether there is a suitable += method on a?
- 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With