Map.withDefault not defaulting?

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

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

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")

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

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

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

1 Like

It seems that Kotlin already has an interface called MapWithDefault. I’m sure many people would be happy if withDefault would return a collection of that type.