'Type mismatch error when adding a map value to a variable (Kotlin)
I want to add a value from a MutableMap to the total, but I keep getting Type mismatch: inferred type is Int? but Int was expected error and I don't know how to fix this issue
I tried calling the value as Int
menu[item].toInt()and setting logic in the if statement that checks that the item is indeed Int, but nothing helped.
Please, see the code below
fun main() {
val order = Order()
order.placeOrder("Noodles")
}
val menu: MutableMap<String, Int> = mutableMapOf("Noodles" to 10,
"Vegetables Chef's Choice" to 5,
)
class Order {
var total = 0
fun placeOrder(vararg orderedItems: String) {
for (item in orderedItems) {
if (item in menu) {
total += menu[item]
}
}
}
}
Solution 1:[1]
Your call to menu[item] is a shorthand for menu.get(item) which is defined as Map<K, out V>.get(key: K): V?.
In case no element with the specified key is found in the map, null is returned.
You may fix this by providing a default value, in case the returned value is null, e.g.:
total += menu[item] ?: 0
Map<K, out V> also provides alternatives, which provide Int instead of Int?.
You may use getValue(key: K): V, which throws an NoSuchElementException, when there is no element with the given key.
Alternatively, you can utilize getOrElse(key: K, defaultValue: () -> V): V or getOrDefault(key: K, defaultValue: V): V which both provide a fallback value instead of null.
Examples for the different alternatives below:
total += menu.getValue(item)
total += menu.getOrElse(item) { 0 }
total += menu.getOrDefault(item, 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
