我有一个可变映射,我希望在其中找不到键的默认值 0
我尝试了以下代码withDefault({somevalue})
但仍然返回null
val attributes = mutableMapOf<String, Int>().withDefault({0})
attributes["orange"]=345
println(attributes["orange"])
println(attributes["orang"])
我得到的结果是 345 null
而不是 345 0
我在这里缺少什么?
最佳答案
withDefault 与 getValue 一起使用,而不是与 get 一起使用。 [...]:
val attributes = mutableMapOf<String, Int>().withDefault { 0 }
val result = attributes["orang"]
println(result) // Output: null
val result2 = attributes.getValue("orang")
println(result2) // Output: 0
参见: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 [...]
关于kotlin - Map withDefault 无法在 kotlin 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72555128/