Cannot add an element to a collection with += if it's declared as var


#1

Consider this completely innocent piece of code:

var set = mutableSetOf<String>()
set += "abd"

I get a compiler error:

Error: Kotlin: Assignment operators ambiguity:
public operator fun Set.plus(element: String): Set defined in kotlin.collections
@InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections

This seems silly; how can + and += ever be ambiguous? I clearly typed +=! Also, while using + is legal in that position, it’s not an assignment operator!

How do I make sense of this compiler error and/or language feature?


#2

This expression is ambiguous because it can be interpreted in two ways:

  • either you intended to create a copy of set with the new element set = set + "abd"
  • or you wanted to mutate the existing set: set.plusAssign("abd")

This behavior of += operator is described here: http://kotlinlang.org/docs/reference/operator-overloading.html#assignments


#3

Uh. That is surprising.

Thanks!

I have a bad feeling about this. Those two sequences of statements have subtly different meanings:

val mset = mutableSetOf<String>()
mset += "abd"

var iset = setOf<String>()
iset += "abd"

If the type of a set is visually hidden (because it was inferred), I expect this to be error prone or at least a point of confusion. :confused: