Scala Maps and Option
Look up a key without nulls by using Option.
On this page
Scala collections.
- Look up a key without nulls by using Option.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
Map("Ada" -> 36) builds an immutable map from key-value pairs. Instead of returning null for a missing key, get returns an Option: Some(value) if the key exists, or None if it does not.
Because the possibility of absence is part of the type, the compiler makes you handle it. getOrElse offers a fallback in one step.
Code example
object Main {
def main(args: Array[String]): Unit = {
val ages = Map("Ada" -> 36, "Grace" -> 45)
println(ages.get("Ada"))
println(ages.get("Linus"))
println(ages.getOrElse("Linus", 0))
}
}Some(36) None 0
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
object Main { def main(args: Array[String]): Unit = { val ages = Map("Ada" -> 36, "Grace" -> 45) println(ages.get("Ada")) println(ages.get("Linus")) println(ages.getOrElse("Linus", 0)) }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| An immutable map with two entries. | — | — | |
| The key exists, so the result is wrapped in Some. | — | Some(36) | |
| The key is absent, so the result is None. | — | Some(36) None | |
| Use the fallback value for the missing key. | — | Some(36) None 0 |
Behind the scenes
How Scala processes this code
Scala compiles for the JVM, which invokes the main entry point.
Cost and common mistakes
Lookup is effectively constant time for the default immutable hash map.
- Calling ages("Linus") instead of get throws NoSuchElementException for a missing key.
- Adding to an immutable Map with + returns a new map; the original is unchanged.
Try it yourself
Predict ages.get("Grace").map(a => a + 1).
Reveal answer and reasoning
Some(46); map applies the function only when a value is present.