Coming from C++, Kotlin's withDefault
feature doesn't quite work as expected:
val m = mutableMapOf<Int, MutableList<Int>>().withDefault { mutableListOf() }
...
m.getValue(1).add(2) // does not work if m[1] == null!
Now if for performance reasons I want to do only a single lookup, how can I do that?
A way with two lookups would be
if (m[1] == null) m[1] = mutableListOf(2)
else m[1].add(2)
Is there any way with a single lookup?
Output: