Maps
8 min · Scala
Store values under named keys instead of numbered positions.
Enemy 1 of 5
Creating and reading a Map
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.
Loading editor...