Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the += operator on immutable Set

Tags:

scala

When i do e.g:

var airlines = Set("Qantas", "JetStar", "Air NZ")
airlines += "Virgin"

airlines is an immutable Set.

+= is not defined on the immutable Set trait.

So is += a built-in operator in scala? I mean how does scala know to reassign airlines with a new set("Qantas", "JetStar", "Air NZ", "Virgin") ?

like image 692
Dzhu Avatar asked Oct 10 '11 10:10

Dzhu


2 Answers

If an operator ending with = (e.g. +=) is used but not defined on a class, the Scala compiler will desugar this into e.g.

airlines = airlines + "Virgin"

or, for ++=, we’d have

airlines ++= airlines

desugared into

airlines = airlines ++ airlines

Of course, as dmeister notes, this will only compile if that new expression makes sense. For example, if we deal with vars.

See Scala Reference §6.12.4 Assignment Operators
(<= , >= and != are excluded as special cases, as are patterns also starting with =.)

like image 166
Debilski Avatar answered Nov 16 '22 11:11

Debilski


The += operator creates a new immutable set containing "Virgin" and assigns the new set to the airlines variable. Strictly speaking the existing set object has not changed, but the set objected the airlines variable points to.

Therefore it is important for this to work that airlines is a var variable and not a val, because you cannot reassign to a val variable.

like image 3
dmeister Avatar answered Nov 16 '22 12:11

dmeister