这是食谱应用程序的一部分。我在我写的食谱课上。成分是我写的另一门课。这个想法是将成分及其数量(作为 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/