Start learning free

LESSON 129 OF 677 · DICTIONARIES

Checking for a Key in Scala

Lesson

TL ; DR:

Call map.contains(key) to ask whether a Map has a key. It returns true or false, so it goes in an if.


val capitals = scala.collection.mutable.Map("France" -> "Paris", "Japan" -> "Tokyo")

if (capitals.contains("Japan")) {
    println(capitals("Japan"))   // Tokyo
}

if (!capitals.contains("Spain")) {
    println("No Spain")          // No Spain
}


Full lesson:

Reading a missing key is an error. capitals("Spain") throws a NoSuchElementException.

So check first. capitals.contains("Spain") is true when "Spain" is a key. It is false when it isn't.

Put ! in front for the opposite. !capitals.contains("Spain") is true here.

A value is not a key

contains looks only at the keys. capitals.contains("Paris") is false, because "Paris" is a value.

A key must match exactly, upper and lower case too. capitals.contains("japan") is false.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with ! and contains. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check