Search code examples
kotlinsortedmap

Kotlin Map using Operators


Started playing the weekend with Kotlin and trying to get maps working with operators. Somehow Kotlin tells me I am confusing it with ambiguity.

Here is code that works (syntactically not like I want it to):

var columns = sortedMapOf("a" to 1, "b" to 2)
columns.plusAssign("c" to 3)

And here is code that simply does not compile (but syntactically closer to what I want)

var cs = sortedMapOf(1 to "a", 2 to "b")
cs += Pair(3, "c")

What shorthand operator magic/casting am I missing?

Thanks in advance.


Solution

  • The ambiguity here is because Kotlin can interpret the expression cs += Pair(3, "c") either as operation creating new map from the original map and the given pair and assigning that map back to variable cs = cs.plus(Pair(3, "c")), or as operation mutating the original map cs.plusAssign(Pair(3, "c"))

    To disambiguate this situation, follow the Kotlin motto — make val, not var!

    When you declare cs as val (non-mutable variable), it cannot be reassigned once it has been initialized, so the only operation becomes available here is plusAssign.