kotlindictionaryhashmapmutablemap

Map withDefault not wokring kotlin?


I have a mutable map in which I want a default value 0 for key not found

I tried the below code withDefault({somevalue})but still returns null

val attributes = mutableMapOf<String, Int>().withDefault({0})
attributes["orange"]=345
println(attributes["orange"])
println(attributes["orang"])

The result I get is 345 null instead of 345 0

What is it I am missing here?


Solution

  • withDefault is to be used with getValue and not with get resp. [...]:

    val attributes = mutableMapOf<String, Int>().withDefault { 0 }
    
    val result = attributes["orang"]
    println(result)   // Output: null
    
    val result2 = attributes.getValue("orang")
    println(result2)   // Output: 0
    

    See: withDefault

    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 [...]