开发者

the += operator on immutable Set

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


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 =.)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜