dictionary - Kotlin:mutableMap 无法识别 put()

标签 dictionary kotlin mutable

这是食谱应用程序的一部分。我在我写的食谱课上。成分是我写的另一门课。这个想法是将成分及其数量(作为 Int)存储在映射中。

在类主体中,我将 map 声明为:

var ingredients: Map<Ingredient, Int>

在 init{} 主体中:

ingredients = mutableMapOf<Ingredient, Int>()

问题来了——这个函数是添加一种成分。如果成分已经在 map 中,它会更新数量。 put() 方法应该执行此操作,但 Android Studio 将其变为红色,当我将鼠标悬停在“put”一词上时,它显示“Unresolved reference: put”。加号也有红色下划线。我认为这是可变 map 的基本部分。我哪里出错了? (别担心 - 会有“其他”部分!)

fun addIngredientAndAmount(ingredient: Ingredient, quantity: Int) {
    if (ingredients.containsKey(ingredient)) {
        val oldQuantity = ingredients[ingredient]
        ingredients.put(ingredient, oldQuantity + quantity)
    }
}

最佳答案

您的ingredients 声明为Map,但是Map 表示一个只读接口(interface),因此它没有put 这是 MutableMap 的一个函数。如果将其初始化为 MutableMap 并不重要,因为编译器会检查您为变量指定的类型。

您应该将其声明为:

var ingredients: MutableMap<Ingredient, Int>

您也可以就地初始化它而不是使用 init block :

var ingredients: MutableMap<Ingredient, Int> = mutableMapOf<Ingredient, Int>()

如果这样做,您还可以避免显式声明类型,因为编译器会自动推断它。

var ingredients = mutableMapOf<Ingredient, Int>()

var ingredients: MutableMap<Ingredient, Int> = mutableMapOf()

关于dictionary - Kotlin:mutableMap 无法识别 put(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66734237/

相关文章:

android - 如何将警报对话框或弹出窗口中的事件/值传递给 Android MVP 中的 Activity ?

c# - 是否可以通过 F# 创建第三方可变结构 "more immutable"?

python - 为什么当我将新元素附加到 TUPLE 时它会起作用?

python - 如果值在字典中,则将键添加到数组中,否则将值添加到不同的列表中

matlab - matlab中有双向映射吗?

java - 如何在 Kotlin 中解析微秒精度的 ISO 日期

java - 这两个Java代码Snaps有什么区别吗?

java - 如何为 Map of Sets 的 Java Map 声明 TypeScript 类型?

c# - 使用循环从字典中删除值

kotlin - 尽管有保障,但我的Kotlin代码中仍然存在NullPointerException