What should a lookup return when the key isn't there? Many languages answer "null" and let you find out at runtime, the hard way. Scala answers with a real type: Option[A]. An Option is a box that is in exactly one of two states — Some(value) when there is a value, or None when there isn't. Because the box is part of the type, the compiler makes absence impossible to overlook: Map.get gives you an Option[String], not a String, so you cannot pretend the lookup always succeeds.
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
capitals.get("Japan") // Some(Tokyo) — an Option[String], not a String
capitals.get("Brazil") // None — no crash, just a value saying "nothing here"
Two everyday ways to open the box:
// 1. getOrElse — the value, or your fallback (safe)
capitals.getOrElse("Brazil", "unknown") // "unknown"
// 2. pattern match — handle BOTH states explicitly (safe, and unwraps for you)
capitals.get("Japan") match {
case Some(city) => println(s"got $city") // city is the plain String inside
case None => println("nothing there")
}
The trap:
Scala still lets you demand a value directly — capitals("Brazil") (the bracket-style lookup) skips the Option and just trusts the key exists. When it doesn't, the program dies:
java.util.NoSuchElementException: key not found: Brazil
at scala.collection.immutable.Map$Map2.apply(Map.scala:308)
at Main$.main(Main.scala:4)
Its twin is calling .get on the Option itself — capitals.get("Brazil").get compiles happily and crashes identically:
java.util.NoSuchElementException: None.get
That is the exact crash Option exists to prevent. The rule experienced Scala developers follow: let lookups give you an Option, then leave the box through getOrElse or a match — never through a blind .get.
Assignment
Follow the Coding Tutorial and handle one present and one absent key, every safe way:
- build
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo"), - look up
"Japan"(exists) and"Brazil"(doesn't) with.get, printing the raw Options, - print both again through
getOrElse(key, "unknown")— plain values, no wrapper, - pattern match on each Option:
case Some(city)for the hit,case Nonefor the miss.
The exact expected output is:
found = Some(Tokyo)
missing = None
Japan or default = Tokyo
Brazil or default = unknown
Japan -> Tokyo
Brazil -> not found
Hint
Print with string interpolation: println(s"found = $found") shows the whole box (Some(Tokyo) or None), while case Some(city) => hands you the unwrapped city to print on its own.
Free plan: 30 tutor messages. Premium is unlimited.