Interface Validated<E,A>
- Type Parameters:
E- the type of the error contained in an invalid resultA- the type of the value contained in a valid result
- All Known Implementing Classes:
Validated.Invalid, Validated.Valid
Validated.Valid) or an error (Validated.Invalid).
Unlike Result, which stops at the first error (fail-fast), Validated supports
applicative-style error accumulation via combine(Validated, BinaryOperator, BiFunction) and product(Validated, BinaryOperator).
This makes it ideal for form/DTO validation where all errors should be reported at once.
Sequential fail-fast composition is still available through flatMap(Function).
This interface is NullMarked: all types are non-null by default.
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic final recordRepresents an invalid result containing an error of typeE.static final recordRepresents a valid result containing a value of typeA. -
Method Summary
Modifier and TypeMethodDescriptioncollector(BinaryOperator<E> errMerge) Returns aCollectorthat accumulates a stream ofValidated<E, A>into a singleValidated<E, List<A>>, collecting all valid values and merging all errors left-to-right usingerrMerge.combine(Validated<E, B> other, BinaryOperator<E> errMerge, BiFunction<A, B, C> valueMerge) Combines thisValidatedwithother, accumulating errors and merging values.static <E,A, B, C, R>
Validated<E, R> combine3(Validated<E, A> va, Validated<E, B> vb, Validated<E, C> vc, BinaryOperator<E> errMerge, TriFunction<? super A, ? super B, ? super C, ? extends R> valueMerge) Combines three independentValidatedvalues, accumulating all errors.static <E,A, B, C, D, R>
Validated<E, R> combine4(Validated<E, A> va, Validated<E, B> vb, Validated<E, C> vc, Validated<E, D> vd, BinaryOperator<E> errMerge, QuadFunction<? super A, ? super B, ? super C, ? super D, ? extends R> valueMerge) Combines four independentValidatedvalues, accumulating all errors.Fail-fast sequential composition: appliesmapperto the value ifValidated.Valid.default <R> RFolds this container to a single value by applying the appropriate function.static <E,A> Validated <E, A> fromOption(Option<? extends A> option, E errorIfNone) Converts anOptionto aValidated.static <E,A> Validated <E, A> fromResult(Result<A, E> result) Converts aResultto aValidated.static <E,A> Validated <E, A> Converts aTryto aValidated.default Aget()Retrieves the value if this isValidated.Valid.default EgetError()Retrieves the error if this isValidated.Invalid.default AReturns the success value if present, orfallbackotherwise.default AgetOrElseGet(Supplier<A> supplier) Returns the success value if present, or the value produced bysupplierotherwise.default AReturns the success value if present, ornullotherwise.default AgetOrThrow(Function<E, ? extends RuntimeException> exMapper) Returns the success value if present, or throws an exception mapped from the error.static <E,A> Validated <E, A> invalid(E error) Creates anValidated.Invalidinstance wrapping the given error.static <E,A> Validated <NonEmptyList<E>, A> invalidNel(E error) default booleanReturnstrueif this instance isValidated.Invalid.default booleanReturnstrueif this instance is the success (Validated.Valid) variant.default booleanisValid()Returnstrueif this instance isValidated.Valid.default voidExecutes one of the two consumers based on the active variant.product(Validated<E, B> other, BinaryOperator<E> errMerge) Combines thisValidatedwithother, accumulating errors when both are invalid.sequence(Iterable<Validated<E, A>> validated, BinaryOperator<E> errMerge) Transforms an iterable ofValidated<E, A>into a singleValidated<E, List<A>>.sequence(Stream<Validated<E, A>> validated, BinaryOperator<E> errMerge) Transforms a stream ofValidated<E, A>into a singleValidated<E, List<A>>.static <E,A> Validated <NonEmptyList<E>, List<A>> sequenceNel(Iterable<Validated<NonEmptyList<E>, A>> validated) Sequences anIterableofValidated<NonEmptyList<E>, A>into a singleValidated<NonEmptyList<E>, List<A>>, accumulating all errors usingNonEmptyList.concat(NonEmptyList).stream()Returns a single-element stream of the success value, or an empty stream on error.toEither()Converts thisValidatedto anEither.toOption()Converts this container to anOption.toResult()Converts thisValidatedto aResult.Converts thisValidatedto aTry.traverse(Iterable<A> values, Function<? super A, Validated<E, B>> mapper, BinaryOperator<E> errMerge) Maps each element of an iterable throughmapperand collects the results into aValidated<E, List<B>>, accumulating all errors.traverseCollector(Function<? super A, Validated<E, B>> mapper, BinaryOperator<E> errMerge) Returns aCollectorthat maps each input element throughmapperand accumulates the results into a singleValidated<E, List<B>>, collecting all valid values and merging all errors left-to-right usingerrMerge.static <E,A, B> Validated <NonEmptyList<E>, List<B>> traverseNel(Iterable<A> values, Function<? super A, Validated<NonEmptyList<E>, B>> mapper) Maps each element ofvaluesthroughmapperand accumulates the results into aValidated<NonEmptyList<E>, List<B>>, accumulating all errors usingNonEmptyList.concat(NonEmptyList).static <E,A> Validated <E, A> valid(A value) Creates aValidated.Validinstance wrapping the given value.
-
Method Details
-
valid
Creates aValidated.Validinstance wrapping the given value.- Type Parameters:
E- the error typeA- the value type- Parameters:
value- the non-null value- Returns:
- a
Validatedin the valid state - Throws:
NullPointerException- ifvalueisnull
-
invalid
Creates anValidated.Invalidinstance wrapping the given error.- Type Parameters:
E- the error typeA- the value type- Parameters:
error- the non-null error- Returns:
- a
Validatedin the invalid state - Throws:
NullPointerException- iferrorisnull
-
isSuccess
default boolean isSuccess()Returnstrueif this instance is the success (Validated.Valid) variant. -
isValid
default boolean isValid()Returnstrueif this instance isValidated.Valid.- Returns:
trueforValid,falseforInvalid
-
isInvalid
default boolean isInvalid()Returnstrueif this instance isValidated.Invalid.- Returns:
trueforInvalid,falseforValid
-
get
Retrieves the value if this isValidated.Valid.- Returns:
- the contained value
- Throws:
NoSuchElementException- if this isValidated.Invalid
-
getError
Retrieves the error if this isValidated.Invalid.- Returns:
- the contained error
- Throws:
NoSuchElementException- if this isValidated.Valid
-
map
- Type Parameters:
B- the new value type- Parameters:
mapper- the mapping function- Returns:
- a new
Validatedwith the mapped value, or the original error
-
mapError
- Type Parameters:
F- the new error type- Parameters:
mapper- the error mapping function- Returns:
- a new
Validatedwith the mapped error, or the original value
-
flatMap
Fail-fast sequential composition: appliesmapperto the value ifValidated.Valid. If this isValidated.Invalid, the error is propagated without callingmapper.- Type Parameters:
B- the new value type- Parameters:
mapper- a function that maps the value to a newValidated- Returns:
- the result of
mapperif valid, otherwise this invalid
-
product
Combines thisValidatedwithother, accumulating errors when both are invalid.Combination semantics this other result Valid Valid Valid(Tuple2(a, b)) Valid Invalid Invalid(other.error) Invalid Valid Invalid(this.error) Invalid Invalid Invalid(errMerge(this.error, other.error)) - Type Parameters:
B- the value type of the otherValidated- Parameters:
other- the otherValidatedto combine witherrMerge- a function to merge two errors when both are invalid- Returns:
- a
Validatedcontaining aTuple2of values, or an accumulated error
-
combine
default <B,C> Validated<E,C> combine(Validated<E, B> other, BinaryOperator<E> errMerge, BiFunction<A, B, C> valueMerge) Combines thisValidatedwithother, accumulating errors and merging values. Implemented asproduct(other, errMerge).map(t -> valueMerge.apply(t._1(), t._2())).- Type Parameters:
B- the value type of the otherValidatedC- the result value type- Parameters:
other- the otherValidatedto combine witherrMerge- a function to merge two errors when both are invalidvalueMerge- a function to merge two values when both are valid- Returns:
- a
Validatedwith the merged value, or an accumulated error
-
peek
-
peekError
-
toResult
Converts thisValidatedto aResult.Validated.Validmaps toResult.Ok;Validated.Invalidmaps toResult.Err.- Returns:
- a
Resultequivalent of thisValidated
-
toTry
Converts thisValidatedto aTry.Validated.Validmaps toTry.success(V);Validated.Invalidmaps toTry.failure(Throwable)using the provided error mapper.- Parameters:
errorMapper- maps the error to aThrowable- Returns:
- a
Tryequivalent of thisValidated - Throws:
NullPointerException- iferrorMapperis null or returns null
-
toEither
Converts thisValidatedto anEither.Validated.Validmaps toEither.right(R);Validated.Invalidmaps toEither.left(L). Useful as an escape hatch from error-accumulating validation into the short-circuitingEitherworld, for example to applyflatMapafter validation succeeds.- Returns:
- an
Either<E, A>equivalent of thisValidated
-
fromResult
Converts aResultto aValidated.Result.Okmaps toValidated.Valid;Result.Errmaps toValidated.Invalid.- Type Parameters:
E- the error typeA- the value type- Parameters:
result- the result to convert; must not be null- Returns:
- the equivalent
Validated - Throws:
NullPointerException- ifresultis null
-
fromOption
Converts anOptionto aValidated.Option.Somemaps toValidated.Valid;Option.none()maps toValidated.Invalidusing the provided error.- Type Parameters:
E- the error typeA- the value type- Parameters:
option- the option to convert; must not be nullerrorIfNone- the error to use if the option is empty- Returns:
- the equivalent
Validated - Throws:
NullPointerException- ifoptionis null
-
fromTry
Converts aTryto aValidated.Try.success(V)maps toValidated.Valid;Try.failure(Throwable)maps toValidated.Invalidusing the provided error mapper.- Type Parameters:
E- the error typeA- the value type- Parameters:
t- the try to convert; must not be nullerrorMapper- maps the throwable to an error; must not return null- Returns:
- the equivalent
Validated - Throws:
NullPointerException- iftorerrorMapperis null
-
sequence
static <E,A> Validated<E,List<A>> sequence(Iterable<Validated<E, A>> validated, BinaryOperator<E> errMerge) Transforms an iterable ofValidated<E, A>into a singleValidated<E, List<A>>. All errors are accumulated usingerrMerge; all valid values are collected in order. If any element isValidated.Invalid, no values are collected and the accumulated error is returned.- Type Parameters:
E- the error typeA- the value type- Parameters:
validated- the iterable of validated values; must not be null or contain null elementserrMerge- a function to merge two errors; used when multiple elements are invalid- Returns:
Valid(List<A>)if all elements are valid, orInvalid(accumulatedError)- Throws:
NullPointerException- ifvalidatedorerrMergeis null, or ifvalidatedcontains a null element
-
sequence
static <E,A> Validated<E,List<A>> sequence(Stream<Validated<E, A>> validated, BinaryOperator<E> errMerge) Transforms a stream ofValidated<E, A>into a singleValidated<E, List<A>>. All errors are accumulated usingerrMerge; all valid values are collected in order.- Type Parameters:
E- the error typeA- the value type- Parameters:
validated- the stream of validated values; must not be null or contain null elementserrMerge- a function to merge two errors- Returns:
Valid(List<A>)if all elements are valid, orInvalid(accumulatedError)- Throws:
NullPointerException- ifvalidatedorerrMergeis null, or if the stream contains a null element
-
traverse
static <E,A, Validated<E,B> List<B>> traverse(Iterable<A> values, Function<? super A, Validated<E, B>> mapper, BinaryOperator<E> errMerge) Maps each element of an iterable throughmapperand collects the results into aValidated<E, List<B>>, accumulating all errors.- Type Parameters:
E- the error typeA- the input element typeB- the mapped value type- Parameters:
values- the iterable of input values; must not be nullmapper- a function that maps each value to aValidated; must not return nullerrMerge- a function to merge two errors- Returns:
Valid(List<B>)if all mappings succeed, orInvalid(accumulatedError)- Throws:
NullPointerException- if any argument is null or if the mapper returns null
-
collector
static <E,A> Collector<Validated<E,A>, ?, Validated<E, collectorList<A>>> (BinaryOperator<E> errMerge) Returns aCollectorthat accumulates a stream ofValidated<E, A>into a singleValidated<E, List<A>>, collecting all valid values and merging all errors left-to-right usingerrMerge.Compatible with parallel streams: partial results from each split are combined via
errMergeon errors and list concatenation on values.- Type Parameters:
E- the error typeA- the value type- Parameters:
errMerge- a function to merge two errors; must not returnnull- Returns:
- a
CollectorproducingValid(List<A>)if all elements are valid, orInvalid(accumulatedError)otherwise - Throws:
NullPointerException- iferrMergeis null
-
traverseCollector
static <E,A, Collector<A, ?, Validated<E,B> List<B>>> traverseCollector(Function<? super A, Validated<E, B>> mapper, BinaryOperator<E> errMerge) Returns aCollectorthat maps each input element throughmapperand accumulates the results into a singleValidated<E, List<B>>, collecting all valid values and merging all errors left-to-right usingerrMerge.The mapper is applied eagerly during accumulation, so parallel streams benefit from parallel mapping. Compatible with parallel streams.
- Type Parameters:
E- the error typeA- the input element typeB- the mapped value type- Parameters:
mapper- a function mapping each element to aValidated; must not returnnullerrMerge- a function to merge two errors; must not returnnull- Returns:
- a
CollectorproducingValid(List<B>)if all mappings succeed, orInvalid(accumulatedError)otherwise - Throws:
NullPointerException- ifmapperorerrMergeis null
-
invalidNel
Creates anValidated.InvalidValidatedwhose error is a singletonNonEmptyListcontainingerror.This is the canonical way to start error accumulation with
NonEmptyListerrors: multipleinvalidNelresults can be combined withcombine(Validated, BinaryOperator, BiFunction)usingNonEmptyList.concat(NonEmptyList)as the merger, and the resulting error list is always non-empty.Validated<NonEmptyList<String>, String> v1 = Validated.invalidNel("email is required"); Validated<NonEmptyList<String>, String> v2 = Validated.invalidNel("name is required"); Validated<NonEmptyList<String>, Form> combined = v1.combine(v2, NonEmptyList::concat, (e, n) -> new Form(e, n)); // combined.getError() → NonEmptyList["email is required", "name is required"]- Type Parameters:
E- the error element typeA- the value type- Parameters:
error- the single error to wrap; must not benull- Returns:
- an
Invalid<NonEmptyList<E>, A> - Throws:
NullPointerException- iferrorisnull
-
sequenceNel
static <E,A> Validated<NonEmptyList<E>, List<A>> sequenceNel(Iterable<Validated<NonEmptyList<E>, A>> validated) Sequences anIterableofValidated<NonEmptyList<E>, A>into a singleValidated<NonEmptyList<E>, List<A>>, accumulating all errors usingNonEmptyList.concat(NonEmptyList).Convenience wrapper around
sequence(Iterable, BinaryOperator)that supplies the NEL merger automatically.- Type Parameters:
E- the error element typeA- the value type- Parameters:
validated- the iterable of validated values; must not be null or contain null elements- Returns:
Valid(List<A>)if all elements are valid, orInvalid(NonEmptyList<E>)with all accumulated errors- Throws:
NullPointerException- ifvalidatedis null or contains a null element
-
traverseNel
static <E,A, Validated<NonEmptyList<E>, List<B>> traverseNelB> (Iterable<A> values, Function<? super A, Validated<NonEmptyList<E>, B>> mapper) Maps each element ofvaluesthroughmapperand accumulates the results into aValidated<NonEmptyList<E>, List<B>>, accumulating all errors usingNonEmptyList.concat(NonEmptyList).Convenience wrapper around
traverse(Iterable, Function, BinaryOperator)that supplies the NEL merger automatically.- Type Parameters:
E- the error element typeA- the input element typeB- the mapped value type- Parameters:
values- the iterable of input values; must not be nullmapper- a function mapping each value to aValidated; must not return null- Returns:
Valid(List<B>)if all mappings succeed, orInvalid(NonEmptyList<E>)with all accumulated errors- Throws:
NullPointerException- if any argument is null or if the mapper returns null
-
combine3
static <E,A, Validated<E,B, C, R> R> combine3(Validated<E, A> va, Validated<E, B> vb, Validated<E, C> vc, BinaryOperator<E> errMerge, TriFunction<? super A, ? super B, ? super C, ? extends R> valueMerge) Combines three independentValidatedvalues, accumulating all errors.All three inputs are always evaluated — no short-circuit. If any are
Validated.Invalid, all errors are merged left-to-right usingerrMerge. If all areValidated.Valid,valueMergeis applied and the result is returned asValidated.Valid.Validated<NonEmptyList<String>, Form> result = Validated.combine3( validateUsername(username), validateEmail(email), validateAge(age), NonEmptyList::concat, Form::new );- Type Parameters:
E- the error typeA- the value type of the firstValidatedB- the value type of the secondValidatedC- the value type of the thirdValidatedR- the result value type- Parameters:
va- the first validated value; must not benullvb- the second validated value; must not benullvc- the third validated value; must not benullerrMerge- a function to merge two errors when multiple inputs are invalid; must not benullor returnnullvalueMerge- a function to combine three values when all inputs are valid; must not benull- Returns:
Valid(valueMerge(a, b, c))if all are valid, orInvalid(mergedError)otherwise- Throws:
NullPointerException- if any argument isnull
-
combine4
static <E,A, Validated<E,B, C, D, R> R> combine4(Validated<E, A> va, Validated<E, B> vb, Validated<E, C> vc, Validated<E, D> vd, BinaryOperator<E> errMerge, QuadFunction<? super A, ? super B, ? super C, ? super D, ? extends R> valueMerge) Combines four independentValidatedvalues, accumulating all errors.All four inputs are always evaluated — no short-circuit. If any are
Validated.Invalid, all errors are merged left-to-right usingerrMerge. If all areValidated.Valid,valueMergeis applied and the result is returned asValidated.Valid.Validated<NonEmptyList<String>, Form> result = Validated.combine4( validateUsername(username), validateEmail(email), validateAge(age), validateCountry(country), NonEmptyList::concat, Form::new );- Type Parameters:
E- the error typeA- the value type of the firstValidatedB- the value type of the secondValidatedC- the value type of the thirdValidatedD- the value type of the fourthValidatedR- the result value type- Parameters:
va- the first validated value; must not benullvb- the second validated value; must not benullvc- the third validated value; must not benullvd- the fourth validated value; must not benullerrMerge- a function to merge two errors when multiple inputs are invalid; must not benullor returnnullvalueMerge- a function to combine four values when all inputs are valid; must not benull- Returns:
Valid(valueMerge(a, b, c, d))if all are valid, orInvalid(mergedError)otherwise- Throws:
NullPointerException- if any argument isnull
-
getOrElse
Returns the success value if present, orfallbackotherwise.- Parameters:
fallback- the non-null fallback value- Returns:
- the success value, or
fallbackif this is the error variant - Throws:
NullPointerException- iffallbackisnull
-
getOrElseGet
Returns the success value if present, or the value produced bysupplierotherwise.- Parameters:
supplier- supplier of the fallback value; must not returnnull- Returns:
- the success value, or the value produced by
supplier - Throws:
NullPointerException- ifsupplierisnullor returnsnull
-
getOrNull
Returns the success value if present, ornullotherwise.- Returns:
- the success value or
null
-
getOrThrow
Returns the success value if present, or throws an exception mapped from the error.- Parameters:
exMapper- maps the error to aRuntimeException; must not returnnull- Returns:
- the success value
- Throws:
NullPointerException- ifexMapperisnullor returnsnullRuntimeException- the exception produced byexMapperon the error variant
-
stream
-
fold
Folds this container to a single value by applying the appropriate function.- Type Parameters:
R- the result type- Parameters:
onSuccess- applied to the success value; must not returnnullonError- applied to the error value; must not returnnull- Returns:
- the result of the applied function
- Throws:
NullPointerException- if either function isnullor returnsnull
-
match
Executes one of the two consumers based on the active variant.- Parameters:
onSuccess- called with the success valueonError- called with the error value- Throws:
NullPointerException- if either consumer isnull
-
toOption
Converts this container to anOption. The success variant maps toOption.Some; the error variant maps toOption.none().- Returns:
- an
Optioncontaining the success value, or empty
-