-
Notifications
You must be signed in to change notification settings - Fork 136
X Option
some : Some represents a value that is present
Option.some(10) //Some[10]
none : None represents the absence of a value
Option.none() //None[]
The JDK has Optional, which suffers from a number of flaws which are not present in cyclops X's Option type.
- Optional::get - throws a NoSuchElementException when called on Optional::empty
- Null is not a valid value :
java Optional.of(10).map(i->null)
results in Optional.empty rather than Optional[null]
Cyclops Option does not provide a direct get method, instead overloads are provided where users can provide a default value as an alternative. E.g.
Option.some(10)
.orElse(-10);
Option.some(10)
.orElseGet(()->-10);
Another alternative is to use a fold, which takes a Function and a Supplier. The Function is executed when a value is present in the Option (the input parameter is the value), the Supplier is called when no value is present.
Option.some(10)
.fold(i->i+5,()->-1); //15
Option.none()
.fold(i->i+5,()->-1); //-1
Not allowing Optional to store null introduces a special case within Optionals behaviour which breaks the generalized behaviour (as defined in the Monad laws) present in most other Optional / Option implementations. This may cause problems when using Optional with APIs where null is a valid value, the code below results in a RuntimeException.
Optional.of(null);
In cyclops null is a valid value for an Option.some instance. The code below does not throw any Exception
Option.some(null);
Like with Optional, conditional conversion of nullable values to Option.some / Option.none instances can be done via
Option.ofNullable(nullableValue);
oops - my bad