4

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.

5
  • I understand the question, but I would just resolve it with columns.put("c", 3); Commented Nov 1, 2015 at 7:46
  • JB, agreed - there is a 100 ways to make it work (functionally). The point is that Kotlin supports the += operator and that it should work, and I want to use it as it reads mathematically I want my code to read. Also, by me not getting it to work means that I am conceptually missing something Commented Nov 1, 2015 at 7:50
  • I relayed your question on the kotlin slack channel. Let's see if an answer comes up... Commented Nov 1, 2015 at 7:53
  • JB - in follow up to your answer of columns.put... even more natural would be code cs[4] = "f" Commented Nov 1, 2015 at 8:29
  • cs[4] = "c" also won't allocate an aditional object. Commented Nov 1, 2015 at 11:49

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you confirm that there's no way to resolve the ambiguity if cs is a var and not a val?
Ilya - thanks - confirmed and working. Wow! Don't quite know what to make of it (definitely is a change of pattern for everything I was used to in pretty much every other language)... but will look out for it now. The other thing is that why can it figure out cs.plusAssign() but not cs.+= with the same Pair parameter. I would naturally have thought that it knew what was coming and where it was going.
Sorry - the second question you answered already... was just thinking out loud.
Also note that technically there is no problem for a compiler to resolve this issue automatically. But Kotlin reports ambiguity on purpose, just to ease the life of a human reader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.