選項作為集合

Options 有一些有用的高階函式,可以通過將選項視為具有零個或一個專案的集合來輕鬆理解 - 其中 None 的行為類似於空集合,而 Some(x) 的行為類似於具有單個專案的集合 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