Start learning free

LESSON 129 OF 677 · DICTIONARIES

Checking for a Key in Kotlin

Lesson

TL ; DR:

Write key in map to ask whether a map has a key. The answer is true or false, so it goes in an if.


val capitals = mutableMapOf("France" to "Paris", "Japan" to "Tokyo")

if ("Japan" in capitals) {
    println(capitals["Japan"])   // Tokyo
}

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


Full lesson:

A missing key gives null. capitals["Spain"] is null, and !! on it crashes the program.

So check first. On a map, in is short for containsKey. The check "Spain" in capitals is true when "Spain" is a key.

!in asks the opposite. "Spain" !in capitals is true here.

A value is not a key

in looks only at the keys. "Paris" in capitals is false, because "Paris" is a value.

To look in the values, write "Paris" in capitals.values.

A key must match exactly, upper and lower case too. "japan" in capitals 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 !in. 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