Interface Option<Value>
- Type Parameters:
Value- The type of the optional value.
- All Known Implementing Classes:
Option.None,Option.Some
A sealed interface representing an optional value with two possible states:
either a value is present ("Some") or absent ("None").
This interface provides a flexible alternative to Optional,
integrating functional-style operations for working with optional values in a more
expressive and composable manner.
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic final recordRepresents a variant of theOptiontype that signifies the absence of a value.static final recordRepresents a container object that holds a non-null value. -
Method Summary
Modifier and TypeMethodDescriptionstatic <V> List<V> collectPresent(Stream<Option<V>> options) Collects all present (non-empty) values from a stream ofOptioninstances into a list.Filters the value of this Option based on the provided predicate.default <NewValue> Option<NewValue> Transforms the current Option value using the provided mapping function and flattens the result.default <Folded> FoldedFolds the current option into a single value by applying the appropriate function depending on whether the option is aSomeor aNone.static <V> Option<V> fromOptional(Optional<V> optional) static <V,E> Option <V> fromResult(Result<? extends V, ? extends E> result) static <V> Option<V> default Valueget()Retrieves the value held by thisOptioninstance if it is of typeSome.default ValueRetrieves the encapsulated value if thisOptioninstance is of typeSome, or returns the provided fallback value if this instance is of typeNone.default ValuegetOrElseGet(Supplier<? extends Value> fallbackSupplier) Retrieves the encapsulated value if thisOptioninstance is of typeSome, or computes and returns a fallback value supplied by the givenfallbackSupplierif this instance is of typeNone.default ValueRetrieves the encapsulated value if thisOptioninstance is of typeSome, or returnsnullif this instance is of typeNone.default ValuegetOrThrow(Supplier<? extends RuntimeException> exceptionSupplier) Retrieves the encapsulated value if thisOptioninstance is of typeSome.default booleanDetermines whether this instance represents a defined value.default booleanisEmpty()Checks if thisOptioninstance represents the absence of a value.default <NewValue> Option<NewValue> Transforms the current Option using the provided mapping function.static <A,B, R> Option <R> map2(Option<? extends A> a, Option<? extends B> b, BiFunction<? super A, ? super B, ? extends R> combiner) Combines the values of two Option instances using the provided combiner function.default voidExecutes one of the provided actions based on the state of this value.static <V> Option<V> none()Creates an instance ofOptionthat represents the absence of a value.static <V> Option<V> ofNullable(V value) Creates an Option instance that encapsulates a given value.Applies the provided action to the value contained in this instance if it is of type Some.Creates a collector that transforms a stream of Option objects into a list of values by extracting the present values and filtering out any absent values.Transforms an iterable ofOption<V>into a singleOption<List<V>>.Converts a stream ofOptionobjects into a singleOptioncontaining aListof values, if allOptioninstances in the stream areOption.Some.static <V> Option<V> some(V value) Creates aOption.Someinstance that encapsulates the given non-null value.stream()Returns a stream representation of the current instance.Converts the current instance of a value or none container into anOptional.toResult(TError errorIfNone) Converts the current option to aResultinstance.Converts the current instance to aTryinstance.Transforms a collection of values of type A into an optional list of values of type B by applying a given mapping function to each element in the input collection.Transforms a stream of values by applying a mapper function that returns anOptionfor each input value.Combines the currentOptioninstance with anotherOptioninstance into a singleOptioncontaining aTuple2of their values, if both options are non-empty.default <B,R> Option <R> zipWith(Option<? extends B> other, BiFunction<? super Value, ? super B, ? extends R> combiner) Combines the values of this Option with the values of another Option using a provided combining function.
-
Method Details
-
some
Creates aOption.Someinstance that encapsulates the given non-null value. UseofNullable(Object)if the value may benull.- Type Parameters:
V- the type of the value to encapsulate- Parameters:
value- the non-null value to encapsulate- Returns:
- a
Some<V>wrapping the provided value - Throws:
NullPointerException- ifvalueisnull(enforced bySome(Object))
-
none
-
ofNullable
Creates an Option instance that encapsulates a given value. If the value is null, it returns a None instance.- Type Parameters:
V- the type of the value to encapsulate- Parameters:
value- the value to be encapsulated; if null, a None instance is returned- Returns:
- an Option containing the provided value if it is non-null, or a None instance if the value is null
-
fromOptional
- Type Parameters:
V- the type of the value that may be present in theOptional- Parameters:
optional- theOptionalto be converted; if theOptionalcontains a value, aSomeinstance is returned, otherwise aNoneinstance is returned- Returns:
- an
Optioncontaining the value from theOptionalif it is present, or an emptyNoneinstance if theOptionalis empty
-
isDefined
default boolean isDefined()Determines whether this instance represents a defined value.- Returns:
trueif this instance is of typeSome<?>and holds a value;falseif it is of typeNoneand does not hold a value.
-
isEmpty
default boolean isEmpty()Checks if thisOptioninstance represents the absence of a value.- Returns:
trueif this instance is of typeNone<?>, indicating no value is present;falseif this instance holds a value.
-
get
Retrieves the value held by thisOptioninstance if it is of typeSome. If the instance is of typeNone, aNoSuchElementExceptionis thrown.- Returns:
- the encapsulated value if this is an instance of
Some - Throws:
NoSuchElementException- if this is an instance ofNone, indicating no value is present
-
getOrElse
Retrieves the encapsulated value if thisOptioninstance is of typeSome, or returns the provided fallback value if this instance is of typeNone.- Parameters:
fallback- the value to return if this instance isNone- Returns:
- the encapsulated value if this instance is a
Some, or the specified fallback value if this instance isNone
-
getOrElseGet
Retrieves the encapsulated value if thisOptioninstance is of typeSome, or computes and returns a fallback value supplied by the givenfallbackSupplierif this instance is of typeNone.- Parameters:
fallbackSupplier- aSupplierthat provides a fallback value if this instance represents the absence of a value- Returns:
- the encapsulated value if this instance is a
Some, or the fallback value computed by thefallbackSupplierif this instance is aNone
-
getOrNull
Retrieves the encapsulated value if thisOptioninstance is of typeSome, or returnsnullif this instance is of typeNone.- Returns:
- the encapsulated value if this instance is a
Some, ornullif this instance is aNone.
-
getOrThrow
Retrieves the encapsulated value if thisOptioninstance is of typeSome. If the instance is of typeNone, it throws an exception provided by the givenexceptionSupplier.- Parameters:
exceptionSupplier- aSupplierthat provides the exception to be thrown if this instance is of typeNone- Returns:
- the encapsulated value if this instance is of type
Some - Throws:
RuntimeException- if this instance is of typeNone, using the exception provided byexceptionSupplier
-
map
Transforms the current Option using the provided mapping function. If the current Option is a Some, applies the provided mapper to its value. If the current Option is a None, returns None without applying the mapper.- Type Parameters:
NewValue- the type of the value in the resulting Option after transformation- Parameters:
mapper- the function to apply to the value if this Option is a Some- Returns:
- a new Option containing the mapped value if this is a Some, or None if this is a None
-
flatMap
Transforms the current Option value using the provided mapping function and flattens the result. If the Option is empty (None), it remains empty. Otherwise, it applies the mapping function to the encapsulated value and returns the resulting Option.- Type Parameters:
NewValue- the type of the element contained in the resulting Option- Parameters:
mapper- the function to apply to the encapsulated value, which produces a new Option- Returns:
- a new Option resulting from applying the mapping function and flattening
- Throws:
NullPointerException- if the mapping function returns null
-
filter
Filters the value of this Option based on the provided predicate. If this Option is a Some and the predicate evaluates to true, the Option is returned as-is. If the predicate evaluates to false, or this Option is a None, an empty Option is returned.- Parameters:
predicate- the predicate used to test the value inside this Option- Returns:
- an Option containing the value if the predicate evaluates to true, otherwise an empty Option
-
peek
-
fold
default <Folded> Folded fold(Supplier<? extends Folded> onNone, Function<? super Value, ? extends Folded> onSome) Folds the current option into a single value by applying the appropriate function depending on whether the option is aSomeor aNone.- Type Parameters:
Folded- The type of the resulting value after folding.- Parameters:
onNone- A supplier to provide a value in case the option isNone.onSome- A function to transform the value in case the option isSome.- Returns:
- The folded value of type
Foldedresulting from applying the appropriate supplier or function.
-
match
Executes one of the provided actions based on the state of this value. If the value is "Some", the provided consumer is executed with the inner value. If the value is "None", the provided runnable is executed.- Parameters:
onNone- the action to execute if the value is "None"onSome- the consumer to execute if the value is "Some", accepting the inner value
-
stream
Returns a stream representation of the current instance. If the instance is of typeSome<Value>, the stream contains the value. If the instance is of typeNone<Value>, the stream is empty.Java 9+ Optional has stream(); this mirrors that. -
Some(v) -> Stream.of(v)-None -> Stream.empty()- Returns:
- a stream containing the value if present, or an empty stream if no value exists
-
toOptional
-
collectPresent
Collects all present (non-empty) values from a stream ofOptioninstances into a list.Equivalent to stream.flatMap(Option::stream).collect(toList()).
- Type Parameters:
V- the type of the values inside theOptioninstances- Parameters:
options- a stream ofOptioninstances- Returns:
- a list containing all present values from the provided stream
-
presentValuesToList
Creates a collector that transforms a stream of Option objects into a list of values by extracting the present values and filtering out any absent values.- Type Parameters:
V- the type of the values inside the Option objects- Returns:
- a Collector that collects present values into a List
-
sequence
Transforms an iterable ofOption<V>into a singleOption<List<V>>. If any element in the input iterable isNone, this method returnsOption.none(). If all elements areSome, the result isOption.some()containing a list of values.- Type Parameters:
V- The type of the values wrapped in theOption.- Parameters:
options- An iterable containingOption<V>elements to be transformed.- Returns:
Option.some()containing a list of values if all elements areSome, orOption.none()if any element isNone.- Throws:
NullPointerException- If theoptionsiterable isnullor containsnullelements.
-
sequence
Converts a stream ofOptionobjects into a singleOptioncontaining aListof values, if allOptioninstances in the stream areOption.Some. If the stream contains anyOption.None, the result will benone().- Type Parameters:
V- the type of elements contained in theOptioninstances- Parameters:
options- a stream ofOptionelements to be sequenced- Returns:
- an
Optioncontaining aListof values if all elements areOption.Some, ornone()if any element in the stream isOption.None - Throws:
NullPointerException- if the stream or any of its elements isnull
-
traverse
Transforms a collection of values of type A into an optional list of values of type B by applying a given mapping function to each element in the input collection. If the mapping function returns aNonefor any element, this method returnsOption.none().- Type Parameters:
A- the type of the elements in the input collectionB- the type of the elements in the resulting optional list- Parameters:
values- the collection of input values to be transformed, must not be nullmapper- the mapping function to apply to each element in the input collection, must not return null orOption.none()for valid outputs- Returns:
- an
Optioncontaining a list of transformed values if all transformations succeed, orOption.none()if the mapping function produces aNonefor any element - Throws:
NullPointerException- ifvaluesormapperis null, or if the mapping function returnsnull
-
traverse
Transforms a stream of values by applying a mapper function that returns anOptionfor each input value. If the mapper function returnsNonefor any value, the entire result isNone. Otherwise, returns aSomewrapping a list of mapped values.- Type Parameters:
A- the type of the input elements in the streamB- the type of the elements in the outputList- Parameters:
values- the stream of input values to traversemapper- the mapping function to transform each input value into anOptionof the output type- Returns:
- an
Optioncontaining aListof transformed values if all inputs are successfully mapped, orNoneif the mapper returnsNonefor any value - Throws:
NullPointerException- ifvaluesormapperis null, or if the mapper function returnsnullfor any input
-
toResult
Converts the current option to aResultinstance.- Type Parameters:
TError- the type of the error value.- Parameters:
errorIfNone- the error value to use if the current option isNone.- Returns:
- a
Resultcontaining the value if this isSome, or an error if this isNone.
-
toTry
Converts the current instance to aTryinstance.- Parameters:
exceptionSupplier- a supplier that provides the exception to be used when the current instance isNone.- Returns:
- a
Tryinstance containing the value if the current instance isSome, or a failedTrywith the supplied exception if the current instance isNone.
-
fromResult
Converts aResultinto anOption.If the given
resultrepresents a successful value (i.e.,isOk()returns true), the value is wrapped in anOption. Otherwise,Option.none()is returned.- Type Parameters:
V- the type of the value contained in the resultE- the type of the error contained in the result- Parameters:
result- theResultto be converted, must not be null- Returns:
- an
Optioncontaining the value from the result if it is successful, or anOption.none()if the result contains an error
-
fromTry
-
zip
Combines the currentOptioninstance with anotherOptioninstance into a singleOptioncontaining aTuple2of their values, if both options are non-empty.- Type Parameters:
B- the type of the value contained in the otherOption- Parameters:
other- the otherOptionto combine with- Returns:
- an
Optioncontaining aTuple2of the values from both options if both are non-empty, otherwise an emptyOption
-
zipWith
default <B,R> Option<R> zipWith(Option<? extends B> other, BiFunction<? super Value, ? super B, ? extends R> combiner) Combines the values of this Option with the values of another Option using a provided combining function.- Type Parameters:
B- the type of the value contained in the other OptionR- the type of the result produced by the combining function- Parameters:
other- the other Option to combine withcombiner- the function to combine the values from this Option and the other Option- Returns:
- an Option containing the result of applying the combining function to the values, or an empty Option if either this Option or the other Option is empty
-
zip
Combines twoOptioninstances into a singleOptioncontaining aTuple2of the values if both options are non-empty. If either option is empty, returns an emptyOption.zip: Option<A> + Option<B> -> Option<Tuple2<A,B>>- Type Parameters:
A- the type of the value in the firstOptionB- the type of the value in the secondOption- Parameters:
a- the firstOptioninstance, must not be nullb- the secondOptioninstance, must not be null- Returns:
- an
Optioncontaining aTuple2of the values if both options are non-empty, otherwise an emptyOption - Throws:
NullPointerException- if eitheraorbis null
-
map2
static <A,B, Option<R> map2R> (Option<? extends A> a, Option<? extends B> b, BiFunction<? super A, ? super B, ? extends R> combiner) Combines the values of two Option instances using the provided combiner function. If either Option is empty (None), the result is an empty Option. If both Options contain values, the combiner function is applied and the result is wrapped in an Option.- Type Parameters:
A- the type of the value contained in the first OptionB- the type of the value contained in the second OptionR- the type of the value contained in the resulting Option- Parameters:
a- the first Option, which may or may not contain a valueb- the second Option, which may or may not contain a valuecombiner- the function used to combine the values of a and b if both are present- Returns:
- an Option containing the result of applying the combiner function to the values of a and b, or an empty Option if either a or b is empty
-