Skip to content

Scala

Option

An Option ins scala represents a value that may or may not exist. It has two possible forms. Some(value) — a value exists. None — no value exists.

val name: Option[String] = Some("Alice")
val missingName: Option[String] = None

Instead of returning null, Scala code often uses Option to make the absence of a value explicit. Common usage

val name = Some("Alice")

name match {
  case Some(n) => println(s"Hello, $n")
  case None    => println("No name found")
}
You can also safely transform an Option with methods like map, getOrElse, and flatMap:

val name: Option[String] = Some("Alice")

val length = name.map(_.length)          // Some(5)
val result = name.getOrElse("Unknown")   // "Alice"