When using .withDefault
on a map, I can set a default value to get using .getValue
when the given key isn't on the map.
The problem arises when I copy that map. The default I set earlier is not preserved.
Why is the wrapping around the default value not preserved when doing a copy? Is this expected behaviour? Is there something here that I am missing?
I did this minimal reproducible example to illustrate the problem:
@Test
fun `withDefault not preserved when copying a map`() {
val map = mapOf<Int, Int>().withDefault { 0 }
assertEquals(map.getValue(1), 0)
val mapCopy = map.toMap()
assertThrows<NoSuchElementException> { mapCopy.getValue(1) }
}
The behaviour of toMap
is exactly as documented:
Returns a new read-only map containing all key-value pairs from the original map.
The default value of the map is not part of the set of key-value pairs. It is a default that's added when the given key is missing from the map. To have this default added to the instance returned by toMap
is not part of its documented behaviour.
Having said that, I can see that it could be desirable to have such a feature. You could suggest one at https://kotl.in/issue.