Option in Scala
Scala's answer to null: a value that is either there or admits it is not.
// Option is the type for "maybe a value", used where null would be.
val ports: Map[String, Int] = Map("http" -> 80, "ssh" -> 22)
// Map.get never throws: it answers Some(value) or None. getOrElse
// then covers the None case and hands back a plain Int.
def portOrDefault(service: String): Int = ports.get(service).getOrElse(8080)
// headOption is a safe head, returning None for an empty list.
def firstService(names: List[String]): Option[String] = names.headOption
// isDefined answers yes or no, and never reaches the value itself.
def isKnown(service: String): Boolean = ports.get(service).isDefined
// A match asks the same question but also binds what is inside.
def describe(service: String): String = ports.get(service) match
case Some(port) => s"$service listens on $port"
case None => s"$service is not configured"
How it works
ports.get(service)hands backSome(port)orNoneinstead of throwing.getOrElse(8080)covers the missing case, andnames.headOptionis a head that is safe on an empty list.isDefinedanswers yes or no, while thematchalso binds the value throughcase Some(port).
Keywords and builtins used here
BooleanIntListMapNoneOptionSomeStringcasedefdescribefirstServiceisKnownmatchportOrDefaultval
The run, in numbers
- Lines
- 17
- Characters to type
- 835
- Tokens
- 122
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 105 seconds.
Step 1 of 3 in Option & Either, step 19 of 27 in Language basics.