Option
s have some useful higher-order functions that can be easily understood by viewing options as collections with zero or one items - where None
behaves like the empty collection, and Some(x)
behaves like a collection with a single item, x
.
val option: Option[String] = ???
option.map(_.trim) // None if option is None, Some(s.trim) if Some(s)
option.foreach(println) // prints the string if it exists, does nothing otherwise
option.forall(_.length > 4) // true if None or if Some(s) and s.length > 4
option.exists(_.length > 4) // true if Some(s) and s.length > 4
option.toList // returns an actual list