Strange behaviour with collection plusAssign operator

I ran into a strange operator ambiguity when using += on a mutable variable of collection (Set, List).

When the variable is not var, it works correctly, because the compiler doesn’t want to release the assignment c += 1 to an = and a +.

There are workarounds (using val or use the named call of the operator (assignPlus), but I think in this case the intention is clear and can’t recall a use case when one means the other way. So the clear precedency goes for the plusAssign.

Is it? Do you want to call

c2 = c2 + 1

or

c2.add(1)

IMO both are equally implied by the += syntax but 1 modifies the original list while the other creates a copy. This can easily lead to confusion and create bugs. There aleady was a discussion about this exact syntax here but I can’t find it right now, but from what I remember the consens was that += isn’t really a good idea to use for lists or mutable lists. The first can easily lead to loads of unintentional copy operations turning a simple loop int o a O(n^2) operation while the other leads to ambiguity.

4 Likes