Class Optional<T>
- Type Parameters:
T
- type of value held inside
- All Implemented Interfaces:
Serializable
Like java.util.Optional
in Java 8, scala.Option
in Scala, and
com.google.common.base.Optional
in Google Guava, this class represents a
value of a given type that may or may not exist. It is used in methods that wish
to optionally return a value, in preference to returning null
.
In fact, the class here is a reimplementation of the essential API of both
java.util.Optional
and com.google.common.base.Optional
. From
java.util.Optional
, it implements:
From com.google.common.base.Optional
it implements:
java.util.Optional
itself was not used because at the time, the
project did not require Java 8. Using com.google.common.base.Optional
has in the past caused serious library version conflicts with Guava that can't
be resolved by shading. Hence this work-alike clone.
- See Also:
-
Method Details
-
empty
- Returns:
- an empty
Optional
-
of
- Parameters:
value
- non-null value to wrap- Returns:
Optional
wrapping this value- Throws:
NullPointerException
- if value is null
-
ofNullable
- Parameters:
value
- value to wrap, which may be null- Returns:
Optional
wrapping this value, which may be empty
-
get
- Returns:
- the value wrapped by this
Optional
- Throws:
NullPointerException
- if this is empty (contains no value)
-
orElse
- Parameters:
other
- value to return if this is empty- Returns:
- this
Optional
's value if present, or else the given value
-
isPresent
public boolean isPresent()- Returns:
- true iff this
Optional
contains a value (non-empty)
-
absent
- Returns:
- an empty
Optional
-
fromNullable
- Parameters:
value
- value to wrap, which may be null- Returns:
Optional
wrapping this value, which may be empty
-
or
- Parameters:
other
- value to return if this is empty- Returns:
- this
Optional
's value if present, or else the given value
-
orNull
- Returns:
- this
Optional
's value if present, or else null
-
equals
-
hashCode
public int hashCode() -
toString
-