Kotlin:mutableMap 无法识别 put()

Don*_*agh 3 dictionary mutable kotlin

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

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

var ingredients: Map<Ingredient, Int>
Run Code Online (Sandbox Code Playgroud)

在 init{} 主体中:

ingredients = mutableMapOf<Ingredient, Int>()
Run Code Online (Sandbox Code Playgroud)

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

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

gpu*_*nto 9

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

您应该将其声明为:

var ingredients: MutableMap<Ingredient, Int>
Run Code Online (Sandbox Code Playgroud)

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

var ingredients: MutableMap<Ingredient, Int> = mutableMapOf<Ingredient, Int>()
Run Code Online (Sandbox Code Playgroud)

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

var ingredients = mutableMapOf<Ingredient, Int>()
Run Code Online (Sandbox Code Playgroud)

或者

var ingredients: MutableMap<Ingredient, Int> = mutableMapOf()
Run Code Online (Sandbox Code Playgroud)