Map.withDefault not defaulting?


#1

Maybe I’m missing something silly, but this prints “null” instead of “0”

val wordCount = mutableMapOf<String, Int>().withDefault { 0 }
println(wordCount["hi"])

#2

This implicit default value is used when the original map doesn’t contain a value for the key specified and a value is obtained with Map.getValue function, for example when properties are delegated to the map.

So you need to use wordCount.getValue("hi")


#3

errr… I’m guessing that the general expectation is Maps use get(). The IntelliJ IDE tells me “don’t use get(), use []” Which I was happy to do.

Won’t everyone fall into the same trap and expect “withDefault” to work when get-ting the usual way? I certainly did.

If I wanted to edit all my getter lines, I’d use getOrDefault


#4

Unfortunately altering the behavior of get when there’s no value for a given key will violate the Map interface contract.


#5

This issue https://youtrack.jetbrains.com/issue/KT-11851 has some prior discussion on this topic.