Start learning free

LESSON 130 OF 677 · DICTIONARIES

Reading a Key That May Be Missing in Kotlin

Lesson

TL ; DR:

map.getOrDefault(key, 0) gives the key's value, or 0 when the key is missing.


val points = mutableMapOf("Ana" to 7)

println(points.getOrDefault("Ana", 0))   // 7
println(points.getOrDefault("Ben", 0))   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points["Ben"] gives null here. Its type is Int?, a number or null. And !! on null crashes the program.

getOrDefault takes a key and a default. It gives the key's value when the key is there. It gives the default when it isn't. Either way, you get a plain Int.

Reading this way doesn't add the key. points still has one key afterwards.

The Elvis operator from Null Safety works too, as in points["Ben"] ?: 0.


Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Read "plums" with getOrDefault and 0 as the default. Store it in plums.

Then print the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 2
    Ctrl + Enter to check