kotlin - Map withDefault 无法在 kotlin 中工作?

标签 kotlin dictionary hashmap mutablemap

我有一个可变映射,我希望在其中找不到键的默认值 0

我尝试了以下代码withDefault({somevalue})但仍然返回null

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

我得到的结果是 345 null 而不是 345 0

我在这里缺少什么?

最佳答案

withDefaultgetValue 一起使用,而不是与 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/

相关文章:

java - Java中根据变量选择数组

android - Twitter API 401 位于/account/verify_credentials

arrays - 如何从 Kotlin JVM 的字节数组中获取无符号整数?

Java 对 List<Value> 的 HashMap 值进行排序

python - 按所有键的唯一性对字典列表进行排序

python - 无法比较类型 'ndarray(dtype=int64)' 和 'int64'

java - java HashMap 的快速失败行为

kotlin - Kotlin覆盖父类(super class)型变量

android - Kotlin 如何创建目录。 MkDir() 不工作

python - 如何获取 `a` 和 `b` 字典的联合键以及 'a' 值?