Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 864
user1210708 Avatar asked Mar 15 '23 07:03

user1210708


1 Answers

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.

like image 196
Ilya Avatar answered Mar 25 '23 04:03

Ilya