Start learning free

LESSON 131 OF 677 · DICTIONARIES

Deleting a Key in Kotlin

Lesson

TL ; DR:

A MutableMap's remove function takes a key. It deletes that key and its value.


val toys = mutableMapOf("ball" to 3, "doll" to 2, "kite" to 1)
toys.remove("kite")

println(toys.size)   // 2
println(toys)        // {ball=3, doll=2}


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call remove on the map with the key. The key and its value go away together.

The size drops by 1. The key is gone, so "kite" in toys is now false.

remove also returns the value it deleted. For a missing key it returns null, and nothing changes.

The map is a val, and you can still delete from it. A val only stops you from giving toys another map.

Watch out: after the delete, toys["kite"] is null. So toys["kite"]!! would crash the program.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print animals.size again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check