Start learning free

LESSON 126 OF 677 · DICTIONARIES

Accessing Dictionary Values in Kotlin

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check