T
- type of value held insidepublic final class Optional<T>
extends Object
implements java.io.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.
Modifier and Type | Method and Description |
---|---|
static <T> Optional<T> |
absent() |
static <T> Optional<T> |
empty() |
boolean |
equals(Object obj) |
static <T> Optional<T> |
fromNullable(T value) |
T |
get() |
int |
hashCode() |
boolean |
isPresent() |
static <T> Optional<T> |
of(T value) |
static <T> Optional<T> |
ofNullable(T value) |
T |
or(T other) |
T |
orElse(T other) |
T |
orNull() |
String |
toString() |
public static <T> Optional<T> empty()
Optional
public static <T> Optional<T> of(T value)
value
- non-null value to wrapOptional
wrapping this valueNullPointerException
- if value is nullpublic static <T> Optional<T> ofNullable(T value)
value
- value to wrap, which may be nullOptional
wrapping this value, which may be emptypublic T get()
Optional
NullPointerException
- if this is empty (contains no value)public T orElse(T other)
other
- value to return if this is emptyOptional
's value if present, or else the given valuepublic boolean isPresent()
Optional
contains a value (non-empty)public static <T> Optional<T> absent()
Optional
public static <T> Optional<T> fromNullable(T value)
value
- value to wrap, which may be nullOptional
wrapping this value, which may be emptypublic T or(T other)
other
- value to return if this is emptyOptional
's value if present, or else the given valuepublic T orNull()
Optional
's value if present, or else nullpublic boolean equals(Object obj)
equals
in class Object
public int hashCode()
hashCode
in class Object
public String toString()
toString
in class Object