Interface Validated<E,A>

Type Parameters:
E - the type of the error contained in an invalid result
A - the type of the value contained in a valid result
All Known Implementing Classes:
Validated.Invalid, Validated.Valid

@NullMarked public sealed interface Validated<E,A> permits Validated.Valid<E,A>, Validated.Invalid<E,A>
A sealed interface representing a validated value that can either be a successful value (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.

  • Method Details

    • valid

      static <E,A> Validated<E,A> valid(A value)
      Creates a Validated.Valid instance wrapping the given value.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      value - the non-null value
      Returns:
      a Validated in the valid state
      Throws:
      NullPointerException - if value is null
    • invalid

      static <E,A> Validated<E,A> invalid(E error)
      Creates an Validated.Invalid instance wrapping the given error.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      error - the non-null error
      Returns:
      a Validated in the invalid state
      Throws:
      NullPointerException - if error is null
    • isSuccess

      default boolean isSuccess()
      Returns true if this instance is the success (Validated.Valid) variant.
    • isValid

      default boolean isValid()
      Returns true if this instance is Validated.Valid.
      Returns:
      true for Valid, false for Invalid
    • isInvalid

      default boolean isInvalid()
      Returns true if this instance is Validated.Invalid.
      Returns:
      true for Invalid, false for Valid
    • get

      default A get()
      Retrieves the value if this is Validated.Valid.
      Returns:
      the contained value
      Throws:
      NoSuchElementException - if this is Validated.Invalid
    • getError

      default E getError()
      Retrieves the error if this is Validated.Invalid.
      Returns:
      the contained error
      Throws:
      NoSuchElementException - if this is Validated.Valid
    • map

      default <B> Validated<E,B> map(Function<A,B> mapper)
      Transforms the value with mapper if Validated.Valid; leaves Validated.Invalid unchanged.
      Type Parameters:
      B - the new value type
      Parameters:
      mapper - the mapping function
      Returns:
      a new Validated with the mapped value, or the original error
    • mapError

      default <F> Validated<F,A> mapError(Function<E,F> mapper)
      Transforms the error with mapper if Validated.Invalid; leaves Validated.Valid unchanged.
      Type Parameters:
      F - the new error type
      Parameters:
      mapper - the error mapping function
      Returns:
      a new Validated with the mapped error, or the original value
    • flatMap

      default <B> Validated<E,B> flatMap(Function<A, Validated<E,B>> mapper)
      Fail-fast sequential composition: applies mapper to the value if Validated.Valid. If this is Validated.Invalid, the error is propagated without calling mapper.
      Type Parameters:
      B - the new value type
      Parameters:
      mapper - a function that maps the value to a new Validated
      Returns:
      the result of mapper if valid, otherwise this invalid
    • product

      default <B> Validated<E, Tuple2<A,B>> product(Validated<E,B> other, BinaryOperator<E> errMerge)
      Combines this Validated with other, accumulating errors when both are invalid.
      Combination semantics
      thisotherresult
      ValidValidValid(Tuple2(a, b))
      ValidInvalidInvalid(other.error)
      InvalidValidInvalid(this.error)
      InvalidInvalidInvalid(errMerge(this.error, other.error))
      Type Parameters:
      B - the value type of the other Validated
      Parameters:
      other - the other Validated to combine with
      errMerge - a function to merge two errors when both are invalid
      Returns:
      a Validated containing a Tuple2 of 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 this Validated with other, accumulating errors and merging values. Implemented as product(other, errMerge).map(t -> valueMerge.apply(t._1(), t._2())).
      Type Parameters:
      B - the value type of the other Validated
      C - the result value type
      Parameters:
      other - the other Validated to combine with
      errMerge - a function to merge two errors when both are invalid
      valueMerge - a function to merge two values when both are valid
      Returns:
      a Validated with the merged value, or an accumulated error
    • peek

      default Validated<E,A> peek(Consumer<A> action)
      Executes action with the value if Validated.Valid; returns this unchanged.
      Parameters:
      action - a consumer of the value
      Returns:
      this instance
    • peekError

      default Validated<E,A> peekError(Consumer<E> action)
      Executes action with the error if Validated.Invalid; returns this unchanged.
      Parameters:
      action - a consumer of the error
      Returns:
      this instance
    • toResult

      default Result<A,E> toResult()
      Converts this Validated to a Result. Validated.Valid maps to Result.Ok; Validated.Invalid maps to Result.Err.
      Returns:
      a Result equivalent of this Validated
    • toTry

      default Try<A> toTry(Function<E, ? extends Throwable> errorMapper)
      Converts this Validated to a Try. Validated.Valid maps to Try.success(V); Validated.Invalid maps to Try.failure(Throwable) using the provided error mapper.
      Parameters:
      errorMapper - maps the error to a Throwable
      Returns:
      a Try equivalent of this Validated
      Throws:
      NullPointerException - if errorMapper is null or returns null
    • toEither

      default Either<E,A> toEither()
      Converts this Validated to an Either.

      Validated.Valid maps to Either.right(R); Validated.Invalid maps to Either.left(L). Useful as an escape hatch from error-accumulating validation into the short-circuiting Either world, for example to apply flatMap after validation succeeds.

      Returns:
      an Either<E, A> equivalent of this Validated
    • fromResult

      static <E,A> Validated<E,A> fromResult(Result<A,E> result)
      Converts a Result to a Validated. Result.Ok maps to Validated.Valid; Result.Err maps to Validated.Invalid.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      result - the result to convert; must not be null
      Returns:
      the equivalent Validated
      Throws:
      NullPointerException - if result is null
    • fromOption

      static <E,A> Validated<E,A> fromOption(Option<? extends A> option, E errorIfNone)
      Converts an Option to a Validated. Option.Some maps to Validated.Valid; Option.none() maps to Validated.Invalid using the provided error.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      option - the option to convert; must not be null
      errorIfNone - the error to use if the option is empty
      Returns:
      the equivalent Validated
      Throws:
      NullPointerException - if option is null
    • fromTry

      static <E,A> Validated<E,A> fromTry(Try<A> t, Function<? super Throwable, E> errorMapper)
      Converts a Try to a Validated. Try.success(V) maps to Validated.Valid; Try.failure(Throwable) maps to Validated.Invalid using the provided error mapper.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      t - the try to convert; must not be null
      errorMapper - maps the throwable to an error; must not return null
      Returns:
      the equivalent Validated
      Throws:
      NullPointerException - if t or errorMapper is null
    • sequence

      static <E,A> Validated<E,List<A>> sequence(Iterable<Validated<E,A>> validated, BinaryOperator<E> errMerge)
      Transforms an iterable of Validated<E, A> into a single Validated<E, List<A>>. All errors are accumulated using errMerge; all valid values are collected in order. If any element is Validated.Invalid, no values are collected and the accumulated error is returned.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      validated - the iterable of validated values; must not be null or contain null elements
      errMerge - a function to merge two errors; used when multiple elements are invalid
      Returns:
      Valid(List<A>) if all elements are valid, or Invalid(accumulatedError)
      Throws:
      NullPointerException - if validated or errMerge is null, or if validated contains a null element
    • sequence

      static <E,A> Validated<E,List<A>> sequence(Stream<Validated<E,A>> validated, BinaryOperator<E> errMerge)
      Transforms a stream of Validated<E, A> into a single Validated<E, List<A>>. All errors are accumulated using errMerge; all valid values are collected in order.
      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      validated - the stream of validated values; must not be null or contain null elements
      errMerge - a function to merge two errors
      Returns:
      Valid(List<A>) if all elements are valid, or Invalid(accumulatedError)
      Throws:
      NullPointerException - if validated or errMerge is null, or if the stream contains a null element
    • traverse

      static <E,A,B> Validated<E,List<B>> traverse(Iterable<A> values, Function<? super A, Validated<E,B>> mapper, BinaryOperator<E> errMerge)
      Maps each element of an iterable through mapper and collects the results into a Validated<E, List<B>>, accumulating all errors.
      Type Parameters:
      E - the error type
      A - the input element type
      B - the mapped value type
      Parameters:
      values - the iterable of input values; must not be null
      mapper - a function that maps each value to a Validated; must not return null
      errMerge - a function to merge two errors
      Returns:
      Valid(List<B>) if all mappings succeed, or Invalid(accumulatedError)
      Throws:
      NullPointerException - if any argument is null or if the mapper returns null
    • collector

      static <E,A> Collector<Validated<E,A>, ?, Validated<E,List<A>>> collector(BinaryOperator<E> errMerge)
      Returns a Collector that accumulates a stream of Validated<E, A> into a single Validated<E, List<A>>, collecting all valid values and merging all errors left-to-right using errMerge.

      Compatible with parallel streams: partial results from each split are combined via errMerge on errors and list concatenation on values.

      Type Parameters:
      E - the error type
      A - the value type
      Parameters:
      errMerge - a function to merge two errors; must not return null
      Returns:
      a Collector producing Valid(List<A>) if all elements are valid, or Invalid(accumulatedError) otherwise
      Throws:
      NullPointerException - if errMerge is null
    • traverseCollector

      static <E,A,B> Collector<A, ?, Validated<E,List<B>>> traverseCollector(Function<? super A, Validated<E,B>> mapper, BinaryOperator<E> errMerge)
      Returns a Collector that maps each input element through mapper and accumulates the results into a single Validated<E, List<B>>, collecting all valid values and merging all errors left-to-right using errMerge.

      The mapper is applied eagerly during accumulation, so parallel streams benefit from parallel mapping. Compatible with parallel streams.

      Type Parameters:
      E - the error type
      A - the input element type
      B - the mapped value type
      Parameters:
      mapper - a function mapping each element to a Validated; must not return null
      errMerge - a function to merge two errors; must not return null
      Returns:
      a Collector producing Valid(List<B>) if all mappings succeed, or Invalid(accumulatedError) otherwise
      Throws:
      NullPointerException - if mapper or errMerge is null
    • invalidNel

      static <E,A> Validated<NonEmptyList<E>, A> invalidNel(E error)
      Creates an Validated.Invalid Validated whose error is a singleton NonEmptyList containing error.

      This is the canonical way to start error accumulation with NonEmptyList errors: multiple invalidNel results can be combined with combine(Validated, BinaryOperator, BiFunction) using NonEmptyList.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 type
      A - the value type
      Parameters:
      error - the single error to wrap; must not be null
      Returns:
      an Invalid<NonEmptyList<E>, A>
      Throws:
      NullPointerException - if error is null
    • sequenceNel

      static <E,A> Validated<NonEmptyList<E>, List<A>> sequenceNel(Iterable<Validated<NonEmptyList<E>, A>> validated)
      Sequences an Iterable of Validated<NonEmptyList<E>, A> into a single Validated<NonEmptyList<E>, List<A>>, accumulating all errors using NonEmptyList.concat(NonEmptyList).

      Convenience wrapper around sequence(Iterable, BinaryOperator) that supplies the NEL merger automatically.

      Type Parameters:
      E - the error element type
      A - 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, or Invalid(NonEmptyList<E>) with all accumulated errors
      Throws:
      NullPointerException - if validated is null or contains a null element
    • traverseNel

      static <E,A,B> Validated<NonEmptyList<E>, List<B>> traverseNel(Iterable<A> values, Function<? super A, Validated<NonEmptyList<E>, B>> mapper)
      Maps each element of values through mapper and accumulates the results into a Validated<NonEmptyList<E>, List<B>>, accumulating all errors using NonEmptyList.concat(NonEmptyList).

      Convenience wrapper around traverse(Iterable, Function, BinaryOperator) that supplies the NEL merger automatically.

      Type Parameters:
      E - the error element type
      A - the input element type
      B - the mapped value type
      Parameters:
      values - the iterable of input values; must not be null
      mapper - a function mapping each value to a Validated; must not return null
      Returns:
      Valid(List<B>) if all mappings succeed, or Invalid(NonEmptyList<E>) with all accumulated errors
      Throws:
      NullPointerException - if any argument is null or if the mapper returns null
    • combine3

      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 independent Validated values, accumulating all errors.

      All three inputs are always evaluated — no short-circuit. If any are Validated.Invalid, all errors are merged left-to-right using errMerge. If all are Validated.Valid, valueMerge is applied and the result is returned as Validated.Valid.

      Validated<NonEmptyList<String>, Form> result = Validated.combine3(
          validateUsername(username),
          validateEmail(email),
          validateAge(age),
          NonEmptyList::concat,
          Form::new
      );
      
      Type Parameters:
      E - the error type
      A - the value type of the first Validated
      B - the value type of the second Validated
      C - the value type of the third Validated
      R - the result value type
      Parameters:
      va - the first validated value; must not be null
      vb - the second validated value; must not be null
      vc - the third validated value; must not be null
      errMerge - a function to merge two errors when multiple inputs are invalid; must not be null or return null
      valueMerge - a function to combine three values when all inputs are valid; must not be null
      Returns:
      Valid(valueMerge(a, b, c)) if all are valid, or Invalid(mergedError) otherwise
      Throws:
      NullPointerException - if any argument is null
    • combine4

      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 independent Validated values, accumulating all errors.

      All four inputs are always evaluated — no short-circuit. If any are Validated.Invalid, all errors are merged left-to-right using errMerge. If all are Validated.Valid, valueMerge is applied and the result is returned as Validated.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 type
      A - the value type of the first Validated
      B - the value type of the second Validated
      C - the value type of the third Validated
      D - the value type of the fourth Validated
      R - the result value type
      Parameters:
      va - the first validated value; must not be null
      vb - the second validated value; must not be null
      vc - the third validated value; must not be null
      vd - the fourth validated value; must not be null
      errMerge - a function to merge two errors when multiple inputs are invalid; must not be null or return null
      valueMerge - a function to combine four values when all inputs are valid; must not be null
      Returns:
      Valid(valueMerge(a, b, c, d)) if all are valid, or Invalid(mergedError) otherwise
      Throws:
      NullPointerException - if any argument is null
    • getOrElse

      default A getOrElse(A fallback)
      Returns the success value if present, or fallback otherwise.
      Parameters:
      fallback - the non-null fallback value
      Returns:
      the success value, or fallback if this is the error variant
      Throws:
      NullPointerException - if fallback is null
    • getOrElseGet

      default A getOrElseGet(Supplier<A> supplier)
      Returns the success value if present, or the value produced by supplier otherwise.
      Parameters:
      supplier - supplier of the fallback value; must not return null
      Returns:
      the success value, or the value produced by supplier
      Throws:
      NullPointerException - if supplier is null or returns null
    • getOrNull

      default A getOrNull()
      Returns the success value if present, or null otherwise.
      Returns:
      the success value or null
    • getOrThrow

      default A getOrThrow(Function<E, ? extends RuntimeException> exMapper)
      Returns the success value if present, or throws an exception mapped from the error.
      Parameters:
      exMapper - maps the error to a RuntimeException; must not return null
      Returns:
      the success value
      Throws:
      NullPointerException - if exMapper is null or returns null
      RuntimeException - the exception produced by exMapper on the error variant
    • stream

      default Stream<A> stream()
      Returns a single-element stream of the success value, or an empty stream on error.
      Returns:
      a stream of the value or empty
    • fold

      default <R> R fold(Function<A,R> onSuccess, Function<E,R> onError)
      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 return null
      onError - applied to the error value; must not return null
      Returns:
      the result of the applied function
      Throws:
      NullPointerException - if either function is null or returns null
    • match

      default void match(Consumer<A> onSuccess, Consumer<E> onError)
      Executes one of the two consumers based on the active variant.
      Parameters:
      onSuccess - called with the success value
      onError - called with the error value
      Throws:
      NullPointerException - if either consumer is null
    • toOption

      default Option<A> toOption()
      Converts this container to an Option. The success variant maps to Option.Some; the error variant maps to Option.none().
      Returns:
      an Option containing the success value, or empty