Skip to content
Peter Nerg edited this page Jul 10, 2015 · 18 revisions

#Option Represents optional values.
Instances of Option are either an instance of Some or None. Some holds a non-null value whilst None holds no value.

The purpose is of Optional/Some/None pattern is to replace the ugly null checking that one is forced to in Java.

An example is the Map interface in Java. Performing a get(...) on the Map will yield either the value of the key or null in case no such key exists.

In Scala you'll get an Option which may contain a value or None in case there was no such key.

Example of usage:
Option<UserData> getUser(String userName)

Some

Represents an Option holding a non-null value.
Null values are not allowed as they're by default a non-value and therefore are mapped to None.
Creating Options of type Some is straightforward.
Either use the implementation directly:
Option<String> option = new Some("Peter is Great!");
or use the factory/apply method from Option:
Option<String> option = Option.apply("Peter is Great!");

None

Represents an empty Option.
Empty in the sense of not holding any value. In Java you would normally represent this by null.
But null is ugly and cannot be used in programming without constant null checking.
None allows for programmatic usage performing no actions. Creating Options of type None is straightforward.
Either use the implementation directly:
Option<String> option = new None<>();
or use the factory/apply method from the Option:
Option<String> option = Option.apply(null);
Note the null value provided to apply will yield an Option of type None.
The factory/apply method is preferred as it will return the singleton None since it anyways cannot represent a state, therefore reducing creation of unnecessary object instances.

###Examples T.B.D

Clone this wiki locally