All lessons

Maps

8 min · Scala

Store values under named keys instead of numbered positions.

Scala · Maps0/5 cleared

Enemy 1 of 5

Creating and reading a Map

A Map lets you look up a value by a name, called a key, instead of by position. Use it when data has natural labels, like a player's stats.

This code builds a Map with a name and a score, then prints the value stored under the key name. Press Run to see it.

Why this works

A `List` is great when order matters and you look things up by position, but plenty of real data is more naturally described by a name than a slot number: a player's stats, a word's dictionary definition, a config setting. A `Map` associates each key with a value and lets you look values up by that key directly, without needing to remember which position they happen to sit at.

`Map("key" -> value, ...)` builds an immutable map from a series of key-value pairs, each written with the `->` arrow. Reading a value back out uses function-call syntax with the key: `player("name")`. Like `List`, Scala's default `Map` is immutable, nothing about it changes after creation.

Looking up a key that doesn't exist throws a runtime exception, the same way an out-of-range list index does. If a key might be missing, Scala's `Map` also has a `.get("key")` method that returns an `Option` (either `Some(value)` or `None`) instead of throwing, which is the safer choice once you're past these very first examples.

You
Pincer Crab
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.