Start learning free

LESSON 130 OF 677 · DICTIONARIES

Reading a Key That May Be Missing in Scala

Lesson

TL ; DR:

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


val points = scala.collection.mutable.Map("Ana" -> 7)

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


Full lesson:

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

points("Ben") can't say that. It throws a NoSuchElementException.

You met getOrElse in the Option lesson. It 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.

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


Your task

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

There are no plums yet. Read "plums" with getOrElse 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