typestar

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

  1. ports.get(service) hands back Some(port) or None instead of throwing.
  2. getOrElse(8080) covers the missing case, and names.headOption is a head that is safe on an empty list.
  3. isDefined answers yes or no, while the match also binds the value through case Some(port).

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Option & Either, step 19 of 27 in Language basics.

← Previous Next →

Option in other languages