Donagh
Donagh

Reputation: 139

Kotlin: mutableMap doesn't recognise put()

This is part of a recipe app. I am in the Recipe class which I have written. Ingredient is another class I have written. The idea is to store the ingredient and its amount (as an Int) in a map.

In the class body I have declared the map as:

var ingredients: Map<Ingredient, Int>

And in the init{} body:

ingredients = mutableMapOf<Ingredient, Int>()

Here is the problem - this function is to add an ingredient. It updates the quantity if the ingredient is already in the map. the put()method should do this but Android Studio is turning it red, and when I mouse over the word 'put' it says 'Unresolved reference: put'. The plus symbol also has a red underline. I thought this was a basic part of the mutable map. Where have I gone wrong? (Don't worry - there will be an 'else' part!)

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

Upvotes: 5

Views: 3379

Answers (1)

gpunto
gpunto

Reputation: 2822

Your ingredients is declared as Map, but Map represents a read-only interface so it has no put which is a function of MutableMap. It doesn't matter if you initialize it as MutableMap, because the compiler checks the type you specified for the variable.

You should declare it as:

var ingredients: MutableMap<Ingredient, Int>

You can also initialize it in place instead of using the init block:

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

If you do so you can also avoid stating the type explicitly, as the compiler will automatically infer it.

var ingredients = mutableMapOf<Ingredient, Int>()

or

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

Upvotes: 11

Related Questions