Kotlin map getOrPut behavior when value is a primitive type
I am trying to learn idiomatic Kotlin and have some experience in C++.
I learnt about MutableMap structure in Kotlin and the associated getOrPut method which seems to have a different behavior (a) if the underlying 'value' is of a primitive type vs (b) the value is of a user defined type.
This was kind of confusing to me.
For example:
val mp = mutableMapOf<String, Int> ()
val key = "randomString"
If I want to add a new key (and increment the count if it already exists), what I thought I would need to do:
mp.getOrPut(key) {0} + 1
But this turned out not to work. I would need to assign the value back, as in:
mp[key] = mp.getOrPut(key) {0} + 1
However, if the map is defined as below:
val newMp = mutableMapOf<String, MutableList<String>> ()
newMp.getOrPut(key) {mutableListOf()}.add("str")
this seems to update the newMp (even though I didn't explicitly assign it as in:
newMp[key] = newMp.getOrPut(key) {mutableListOf()}.add("str")
Is my understanding correct? and why is that? My AI search says, if the object is a primitive type, you must assign explicitly.
Posted Jan 30, 2026, 5:20 AM UTC