1

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?

WISHY
  • 11,067
  • 25
  • 105
  • 197

1 Answers1

3

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

lukas.j
  • 6,453
  • 2
  • 5
  • 24