In Kotlin, you access values in a Map by putting the key in square brackets (the index operator, which calls get(key)):
val scores = mutableMapOf("Alice" to 95, "Bob" to 87)
val aliceScore = scores["Alice"] // 95 (type Int?)
val bobScore = scores["Bob"] // 87 (type Int?)
If the key doesn't exist, the lookup returns null, which is why its type is Int?. Use getOrDefault() (or ?: 0) to provide a fallback:
val score = scores.getOrDefault("Diana", 0) // returns 0 if not found
Check if a key exists with containsKey():
if (scores.containsKey("Alice")) {
println(scores["Alice"])
}
Assignment
Follow the Coding Tutorial and access Alice's score from scores!
Hint
Use scores["Alice"]!! and assign it to aliceScore. The !! turns the Int? into a plain Int.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
