Interface Result<Value,Error>
- Type Parameters:
Value- the type of the value contained in a successful resultError- the type of the error contained in an erroneous result
- All Known Implementing Classes:
Result.Err,Result.Ok
@NullMarked
public sealed interface Result<Value,Error>
permits Result.Ok<Value,Error>, Result.Err<Value,Error>
A generic sealed interface representing a result type that can either be a successful value
(
Result.Ok) or an error (Result.Err).
This is a common functional programming construct that allows for
handling both success and error cases in a unified type.
This interface is NullMarked: all types are non-null by default.
Ok.value is guaranteed non-null; use Option inside the value type
to model an optional successful result.
-
Nested Class Summary
Nested Classes -
Method Summary
Modifier and TypeMethodDescriptionstatic <Value,Error>
Result<Value, Error> err(Error error) Creates aResultinstance representing an erroneous result with the given error value.static <Value,Error>
Result<Value, Error> Deprecated, for removal: This API element is subject to removal in a future version.This overload exists only as a type-inference aid and is no longer needed.Filters the current result based on the specified predicate.Filters the current result by applying a given predicate to its value.Applies the given mapping function to the value of a successfulResultinstance and returns the resultingResult.flatMapError(Function<Error, Result<Value, E2>> mapper) Applies a function to the error of an erroneous result and returns the producedResult.default <Folded> FoldedTransforms the currentResultinstance into a value of typeFoldedby applying one of the provided functions based on the state of the instance.static <V,E> Result <V, E> fromOption(Option<? extends V> opt, E errorIfNone) Converts a Try instance into a Result instance.default Valueget()Retrieves the value contained within thisResultinstance if it represents a successful result.default ErrorgetError()Retrieves the error value of the current instance if it is an Err.default ValueReturns the value contained in thisResultinstance if it represents a successful result.default ValuegetOrElseGet(Supplier<Value> fallbackSupplier) Retrieves the value contained within thisResultinstance if it represents a successful result.default ValuegetOrElseGetWithError(Function<Error, Value> errorMapper) Returns the value of thisOk, or applieserrorMapperto the contained error and returns the result.default @Nullable ValueRetrieves the value contained within thisResultinstance if it represents a successful result, or returnsnullif it represents an erroneous result.default ValuegetOrThrow(Function<Error, ? extends RuntimeException> exceptionMapper) Retrieves the value of the currentResultinstance if it represents a successful result, or throws a custom exception mapped from the contained error if it represents an erroneous result.default booleanisError()Checks if the current instance represents an erroneous result.default booleanisOk()Checks if the current instance represents a successful result.Transforms the value of a successfulResultinstance using the provided mapping function.Transforms the error value of an erroneousResultinstance using the provided mapping function.default voidExecutes one of the providedConsumerfunctions based on the state of theResult.static <Value,Error>
Result<Value, Error> ok(Value value) Creates aResultinstance representing a successful result with the given value.static <Value,Error>
Result<Value, Error> Deprecated, for removal: This API element is subject to removal in a future version.This overload exists only as a type-inference aid and is no longer needed.Returns thisResultif it isOk; otherwise evaluates the given supplier and returns its result.Executes the given action if the currentResultinstance represents a successful result.Executes the given action if the currentResultinstance represents an erroneous result.Converts an erroneousResultinto a successful one by applying the given rescue function to the contained error.recoverWith(Function<Error, Result<Value, E2>> rescue) Converts an erroneousResultinto a newResultby applying the given rescue function to the contained error.Transforms an iterable ofResult<V, E>into a singleResult<List<V>, E>.Transforms a stream ofResult<V, E>into a singleResult<List<V>, E>.swap()Swaps theOkandErrchannels of thisResult.toOption()Converts the current instance into anOption<Value>.Converts the current result into aTryinstance.Maps each element of an iterable throughmapperand collects the results into aResult<List<B>, E>.Maps each element of a stream throughmapperand collects the results into aResult<List<B>, E>.
-
Method Details
-
ok
Creates aResultinstance representing a successful result with the given value. This method is used to indicate that a computation or action has succeeded.- Type Parameters:
Value- the type of the value contained in the successful resultError- the type of the error that would be contained in an erroneous result- Parameters:
value- the non-null value to encapsulate in the successful result- Returns:
- a
Resultinstance of typeOk<Value, Error>containing the provided value - Throws:
NullPointerException- ifvalueisnull
-
ok
@Deprecated(forRemoval=true) static <Value,Error> Result<Value,Error> ok(Value value, Class<Error> errorClassIgnored) Deprecated, for removal: This API element is subject to removal in a future version.This overload exists only as a type-inference aid and is no longer needed. Useok(Object)with an explicit type witness or a typed variable instead:Result.<Value, Error>ok(value)orResult<Value, Error> r = Result.ok(value)Creates an instance ofOkrepresenting a successful result.- Type Parameters:
Value- the type of the value in the success caseError- the type of the error in the error case- Parameters:
value- the value to be wrapped in theOkinstanceerrorClassIgnored- the class object of the error type, ignored in this method- Returns:
- an
Okinstance containing the provided value
-
err
Creates aResultinstance representing an erroneous result with the given error value. This method is used to indicate that a computation or action has failed.- Type Parameters:
Value- the type of the value that would be contained in a successful result, unused hereError- the type of the error contained in the erroneous result- Parameters:
error- the non-null error value to encapsulate in the erroneous result- Returns:
- a
Resultinstance of typeErr<Value, Error>containing the provided error - Throws:
NullPointerException- iferrorisnull
-
err
@Deprecated(forRemoval=true) static <Value,Error> Result<Value,Error> err(Error error, Class<Value> classValueIgnored) Deprecated, for removal: This API element is subject to removal in a future version.This overload exists only as a type-inference aid and is no longer needed. Useerr(Object)with an explicit type witness or a typed variable instead:Result.<Value, Error>err(error)orResult<Value, Error> r = Result.err(error)Creates and returns a new result instance representing an error state.- Type Parameters:
Value- The type of the value that would have been contained in a success state.Error- The type of the error being represented.- Parameters:
error- The error to be encapsulated in the result.classValueIgnored- The ignored class type of the value, typically used for type inference.- Returns:
- A result instance representing an error state containing the provided error.
-
isError
default boolean isError()Checks if the current instance represents an erroneous result.- Returns:
trueif the current instance is of typeErr, indicating an error;falseotherwise.
-
isOk
default boolean isOk()Checks if the current instance represents a successful result.- Returns:
trueif the current instance is of typeOk, indicating success;falseotherwise.
-
get
Retrieves the value contained within thisResultinstance if it represents a successful result. If the instance represents an erroneous result, this method throws aNoSuchElementException.- Returns:
- the non-null value contained in the successful result
- Throws:
NoSuchElementException- if the instance represents an erroneous result
-
getError
Retrieves the error value of the current instance if it is an Err. If the instance is an Ok, calling this method will throw a NoSuchElementException.- Returns:
- the error value of the instance if it is an Err.
- Throws:
NoSuchElementException- if the instance is an Ok.
-
map
Transforms the value of a successfulResultinstance using the provided mapping function. If theResultinstance represents an error, the error remains unchanged.- Type Parameters:
NewValue- the type of the value after applying the mapping function- Parameters:
mapper- the function to apply to the value of the successful result- Returns:
- a new
Resultinstance, containing the mapped value if the original instance was successful, or the same error if the original instance was an error
-
mapError
Transforms the error value of an erroneousResultinstance using the provided mapping function. If theResultinstance represents success, the value remains unchanged.- Type Parameters:
NewError- the type of the error after applying the mapping function- Parameters:
mapper- the function to apply to the error of the erroneous result- Returns:
- a new
Resultinstance, containing the transformed error if the original instance was an error, or the same value if the original instance was successful
-
flatMap
Applies the given mapping function to the value of a successfulResultinstance and returns the resultingResult. If the instance represents an error, the error is propagated without applying the mapping function.- Type Parameters:
NewValue- the type of the value in the resultingResultafter applying the mapping function- Parameters:
mapper- the function to apply to the value of the successfulResultto produce a newResult- Returns:
- a new
Resultinstance returned by applying the mapping function to the value if the original instance was successful, or the same error if the original instance was an error
-
match
Executes one of the providedConsumerfunctions based on the state of theResult. If this instance represents a successful result (of typeOk), theonSuccessfunction will be executed with the value contained in the result. If this instance represents an erroneous result (of typeErr), theonErrorfunction will be executed with the error contained in the result. -
peek
Executes the given action if the currentResultinstance represents a successful result. If the instance is of typeOk, the provided action is applied to the contained value. In both cases, the originalResultinstance is returned unchanged.- Parameters:
action- aConsumerthat accepts the value contained in a successful result- Returns:
- the original
Resultinstance
-
peekError
Executes the given action if the currentResultinstance represents an erroneous result. If the instance is of typeErr, the provided action is applied to the contained error value. In both cases, the originalResultinstance is returned unchanged.- Parameters:
action- aConsumerthat accepts the error contained in an erroneous result- Returns:
- the original
Resultinstance
-
getOrElse
Returns the value contained in thisResultinstance if it represents a successful result. If the instance represents an erroneous result, the provided fallback value is returned instead.- Parameters:
fallback- the fallback value to return if this instance is an erroneous result- Returns:
- the value contained in a successful result, or the fallback value if this instance represents an error
-
getOrElseGet
Retrieves the value contained within thisResultinstance if it represents a successful result. If the instance represents an erroneous result, the value provided by the givenSupplieris returned instead.- Parameters:
fallbackSupplier- aSupplierthat provides the fallback value to use if this instance represents an error- Returns:
- the value contained in a successful result, or the value provided by
fallbackSupplierif this instance represents an error
-
getOrThrow
Retrieves the value of the currentResultinstance if it represents a successful result, or throws a custom exception mapped from the contained error if it represents an erroneous result.- Parameters:
exceptionMapper- a function that maps the error value of an erroneous result to aRuntimeExceptionto be thrown- Returns:
- the value contained in the successful result
- Throws:
RuntimeException- the exception produced byexceptionMapperif the instance represents an error
-
getOrNull
Retrieves the value contained within thisResultinstance if it represents a successful result, or returnsnullif it represents an erroneous result.- Returns:
- the value contained in the successful result, or
nullif this instance represents an error
-
fold
Transforms the currentResultinstance into a value of typeFoldedby applying one of the provided functions based on the state of the instance. If the current instance represents a successful result (of typeOk), theonSuccessfunction is applied to the contained value. If the current instance represents an erroneous result (of typeErr), theonErrorfunction is applied to the contained error.- Type Parameters:
Folded- the type of the value returned by the provided functions- Parameters:
onSuccess- a function to apply to the value of a successful resultonError- a function to apply to the error of an erroneous result- Returns:
- the result of applying the appropriate function, as a value of type
Folded
-
filter
Filters the current result based on the specified predicate. If the result is an instance of Ok and the predicate returns false for the value, a new error result is returned with the specified error value. If the current result does not match Ok or the predicate evaluates to true, the current result is returned unchanged.- Parameters:
predicate- the condition to test the value of the resulterrorIfFalse- the error to return if the predicate evaluates to false- Returns:
- the current result if it is not an Ok instance or the predicate evaluates to true, otherwise a new error result with the specified error value
-
filter
Filters the current result by applying a given predicate to its value. If the result is of type Ok and the predicate evaluates to false, the method transforms it into an Err with the error provided by the errorIfFalse function. If the predicate evaluates to true or the result is already of type Err, the original result is returned.- Parameters:
predicate- the condition to be evaluated on the value wrapped by the Ok result.errorIfFalse- a function to generate an error if the predicate evaluates to false.- Returns:
- a filtered result, returning the same instance if the predicate evaluates to true or the result is Err; otherwise, returns an Err with the provided error value.
-
recover
Converts an erroneousResultinto a successful one by applying the given rescue function to the contained error. If this instance is alreadyOk, it is returned unchanged.- Parameters:
rescue- a function that maps the error value to a recovery value; must not returnnull- Returns:
- an
Okresult with the recovered value, or the originalOkif already successful - Throws:
NullPointerException- ifrescueis null or ifrescuereturnsnull
-
recoverWith
Converts an erroneousResultinto a newResultby applying the given rescue function to the contained error. Unlikerecover(java.util.function.Function<Error, Value>), the rescue function may itself return anErr. If this instance is alreadyOk, it is returned as anOkof the new error type.- Type Parameters:
E2- the error type of the resultingResult- Parameters:
rescue- a function that maps the error to a newResult; must not returnnull- Returns:
- the result of applying
rescueto the error, or anOkwrapping the original value - Throws:
NullPointerException- ifrescueis null or ifrescuereturnsnull
-
or
Returns thisResultif it isOk; otherwise evaluates the given supplier and returns its result. The supplier is not called when this instance isOk.- Parameters:
fallback- a lazy supplier of an alternativeResultevaluated only onErr; must not returnnull- Returns:
- this instance if
Ok, or the result offallback.get()ifErr - Throws:
NullPointerException- iffallbackis null or iffallbackreturnsnull
-
flatMapError
Applies a function to the error of an erroneous result and returns the producedResult. If this instance isOk, it is propagated unchanged (with a potentially different error type). This is the dual offlatMap(java.util.function.Function<Value, codes.domix.fun.Result<NewValue, Error>>): it operates on the error channel instead of the value channel.- Type Parameters:
E2- the error type of the resultingResult- Parameters:
mapper- a function that maps the current error to a newResult; must not returnnull- Returns:
- the mapped result for
Err, or the original value wrapped asOkforOk - Throws:
NullPointerException- ifmapperis null or ifmapperreturnsnull
-
swap
-
getOrElseGetWithError
Returns the value of thisOk, or applieserrorMapperto the contained error and returns the result. UnlikegetOrElseGet(Supplier), the fallback function receives the error value, which is useful for deriving a default from the error itself.This method is intentionally named differently from
getOrElseGet(Supplier)to avoid overload ambiguity when passing a null literal or a Groovy/Kotlin closure.- Parameters:
errorMapper- a function that maps the error to a fallback value- Returns:
- the contained value if
Ok, or the result oferrorMapperifErr
-
toOption
Converts the current instance into anOption<Value>. If the instance represents a successful result (Ok), the contained value is wrapped in anOption. If the instance represents an error (Err), an emptyOptionis returned.- Returns:
- an
Option<Value>containing the value if the instance isOk, or an emptyOptionif the instance isErr.
-
toTry
Converts the current result into aTryinstance. If the current result represents a success, the returnedTrywill contain the success value. If the current result represents an error, the specified function is used to transform the error into aThrowable, and the resultingTrywill represent a failure.- Parameters:
errorToThrowable- aFunctionthat converts the error type to aThrowable. Must not return null.- Returns:
- a
Tryinstance representing a success or failure based on the state of the current result. - Throws:
NullPointerException- iferrorToThrowableis null or iferrorToThrowable.apply()returns null.
-
fromOption
- Type Parameters:
V- The type of the value contained in theOption.E- The type of the error value used in theResult.- Parameters:
opt- TheOptionto convert. Must not be null.errorIfNone- The error value to return if theOptionis empty.- Returns:
- A
Resultthat wraps the value from theOptionif it is defined, or an error containingerrorIfNoneif theOptionis empty.
-
fromTry
Converts a Try instance into a Result instance.- Type Parameters:
V- the type of the value contained in the Try instance- Parameters:
t- the Try instance to be converted; must not be null- Returns:
- a Result instance that represents either the success or failure of the given Try instance
-
sequence
Transforms an iterable ofResult<V, E>into a singleResult<List<V>, E>. If any element is anErr, that error is returned immediately (fail-fast). If all elements areOk, returnsOkcontaining an unmodifiable list of values in encounter order.- Type Parameters:
V- the value typeE- the error type- Parameters:
results- the iterable of results; must not benulland must not containnullelements- Returns:
Ok(List<V>)if all elements areOk, or the firstErrencountered- Throws:
NullPointerException- ifresultsisnullor contains anullelement
-
sequence
Transforms a stream ofResult<V, E>into a singleResult<List<V>, E>. If any element is anErr, that error is returned immediately (fail-fast) and the stream is closed. If all elements areOk, returnsOkcontaining an unmodifiable list of values in encounter order.- Type Parameters:
V- the value typeE- the error type- Parameters:
results- the stream of results; must not benulland must not containnullelements- Returns:
Ok(List<V>)if all elements areOk, or the firstErrencountered- Throws:
NullPointerException- ifresultsisnullor contains anullelement
-
traverse
static <A,B, Result<List<B>,E> E> traverse(Iterable<A> values, Function<? super A, Result<B, E>> mapper) Maps each element of an iterable throughmapperand collects the results into aResult<List<B>, E>. Fails fast on the firstErrreturned by the mapper.- Type Parameters:
A- the input element typeB- the mapped value typeE- the error type- Parameters:
values- the iterable of input values; must not benullmapper- a function that maps each value to aResult; must not benulland must not returnnull- Returns:
Ok(List<B>)if all mappings succeed, or the firstErrproduced by the mapper- Throws:
NullPointerException- ifvaluesormapperisnull, or if the mapper returnsnull
-
traverse
static <A,B, Result<List<B>,E> E> traverse(Stream<A> values, Function<? super A, Result<B, E>> mapper) Maps each element of a stream throughmapperand collects the results into aResult<List<B>, E>. Fails fast on the firstErrreturned by the mapper; the stream is closed in all cases.- Type Parameters:
A- the input element typeB- the mapped value typeE- the error type- Parameters:
values- the stream of input values; must not benullmapper- a function that maps each value to aResult; must not benulland must not returnnull- Returns:
Ok(List<B>)if all mappings succeed, or the firstErrproduced by the mapper- Throws:
NullPointerException- ifvaluesormapperisnull, or if the mapper returnsnull
-