Returns the contained instance if it is present;
defaultValue otherwise. If no default
value should be required because the instance is known to be present, use
#get()instead. For a default value of
null, use
#orNull.
Note about generics: The signature
public T or(T defaultValue) is overly
restrictive. However, the ideal signature,
public S or(S), is not legal
Java. As a result, some sensible operations involving subtypes are compile errors:
Optional optionalInt = getSomeOptionalInt();
As a workaround, it is always safe to cast an
Optional to
Optional. Casting either of the above example
Optional instances to
Optional (where
Number is the desired output type) solves the problem:
Optional optionalInt = (Optional) getSomeOptionalInt();
Comparison to
java.util.Optional: this method is similar to Java 8's
Optional.orElse, but will not accept
null as a
defaultValue(
#orNull must be used instead). As a result, the value returned by this method is
guaranteed non-null, which is not the case for the
java.util equivalent.