An Option
is a data structure that contains either a single value, or no value at all. An Option
can be thought of as collections of zero or one elements.
Option is an abstract class with two children: Some
and None
.
Some
contains a single value, and None
contains no value.
Option
is useful in expressions that would otherwise use null
to represent the lack of a concrete value. This protects against a NullPointerException
, and allows the composition of many expressions that might not return a value using combinators such as Map
, FlatMap
, etc.
val countries = Map(
"USA" -> "Washington",
"UK" -> "London",
"Germany" -> "Berlin",
"Netherlands" -> "Amsterdam",
"Japan" -> "Tokyo"
)
println(countries.get("USA")) // Some(Washington)
println(countries.get("France")) // None
println(countries.get("USA").get) // Washington
println(countries.get("France").get) // Error: NoSuchElementException
println(countries.get("USA").getOrElse("Nope")) // Washington
println(countries.get("France").getOrElse("Nope")) // Nope
Option[A]
is sealed and thus cannot be extended. Therefore it's semantics are stable and can be relied on.