Package ch.nevis.mobile.sdk.api.util
Interface Optional<T>
public interface Optional<T>
A container object which may or may not contain a non-null value.
If a value is present,
isPresent()
will return true
and
get()
will return the value.
Additional methods that depend on the presence or absence of a contained
value are provided, such as orElse(Object)
(return a default value if value not present).
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Optional<T>
empty()
Returns an emptyOptional
instance.get()
If a value is present in thisOptional
, returns the value, otherwise throwsNoSuchElementException
.boolean
Returntrue
if there is a value present, otherwisefalse
.static <T> Optional<T>
of
(T value) Returns anOptional
with the specified present non-null value.static <T> Optional<T>
ofNullable
(T value) Returns anOptional
describing the specified value, if non-null, otherwise returns an emptyOptional
.Return the value if present, otherwise returnother
.
-
Method Details
-
get
T get()If a value is present in thisOptional
, returns the value, otherwise throwsNoSuchElementException
.- Returns:
- the non-null value held by this
Optional
- Throws:
NoSuchElementException
- if there is no value present- See Also:
-
isPresent
boolean isPresent()Returntrue
if there is a value present, otherwisefalse
.- Returns:
true
if there is a value present, otherwisefalse
-
orElse
Return the value if present, otherwise returnother
.- Parameters:
other
- the value to be returned if there is no value present, may be null- Returns:
- the value, if present, otherwise
other
-
empty
Returns an emptyOptional
instance. No value is present for this Optional. Though it may be tempting to do so, avoid testing if an object is empty by comparing with==
against instances returned byOption.empty()
. There is no guarantee that it is a singleton. Instead, useisPresent()
.- Type Parameters:
T
- Type of the non-existent value- Returns:
- an empty
Optional
-
of
Returns anOptional
with the specified present non-null value.- Type Parameters:
T
- the class of the value- Parameters:
value
- the value to be present, which must be non-null- Returns:
- an
Optional
with the value present - Throws:
NullPointerException
- if value is null
-
ofNullable
Returns anOptional
describing the specified value, if non-null, otherwise returns an emptyOptional
.- Type Parameters:
T
- the class of the value- Parameters:
value
- the possibly-null value to describe- Returns:
- an
Optional
with a present value if the specified value is non-null, otherwise an emptyOptional
-