Say I have a map:
var inventory = mutableMapOf("apples" to 1, "oranges" to 2)
and I want to increment the number of apples by one.
However this does not work:
inventory["apples"]!!++ // Error:(9, 4) Variable expected
This neither:
var apples = inventory["apples"]!!
++apples
println(inventory["apples"]) // prints "1" => the value was not incremented.
Which is surprising, since in Kotlin, numbers are boxed when they are stored in instances of generic objects. I would not expect that a copy is being made.
It seems that the only way is to do something like:
var apples = inventory["apples"]!!
++apples
inventory["apples"] = apples
println(inventory["apples"])
Which both uses two lookups in the map and is extremely ugly and lengthy.
Is there a way to increment a value of a given key using only one lookup?
Also, could someone explain why the first two methods do not work?