Possible Duplicate:
Why Option[T]?
Reference types provide the special value null meaning "absence of a value". Value types have no such value, which is why C# introduced optional value types (along with special syntax for them).
Scala’s Option[T] has three different "null" values: null, None and Some(null). What exactly does this added complexity buy us in terms of safety and expressibility? When would I use which?
Good Scala really only has one null value:
None. Don’t usenull(except for backward compatibility with existing Java code).There are many answers on SO regarding why
Option[T]is useful. For example: see this.The short version:
It makes the optional nature a signature explicit. The following clearly states that we expect that
tcould be “null”:You don’t have to null-check before operations:
(i: Option[Int]) => i.map(_ + 1)works fine whetheriisSome(5)orNone, and preserves theOptionwrapper to indicate that the input could have beenNone(and, thus, the output might beNoneas well).You can compose them easily with other
Options or collections: