Interface Validation<E,T>

Type Parameters:
E - error type - 错误类型
T - value type - 值类型
All Known Implementing Classes:
Validation.Invalid, Validation.Valid

public sealed interface Validation<E,T> permits Validation.Valid<E,T>, Validation.Invalid<E,T>
Validation Monad - Accumulating error validation Validation Monad - 累积错误的验证

A sealed type for validation that accumulates all errors instead of failing fast. Unlike Either, Validation collects multiple errors.

用于验证的密封类型,累积所有错误而不是快速失败。与 Either 不同,Validation 收集多个错误。

Features | 主要功能:

  • Error accumulation - 错误累积
  • Applicative functor operations - 应用函子操作
  • Combine multiple validations - 组合多个验证
  • Convert to Either - 转换为 Either

Usage Examples | 使用示例:

// Define validations
Validation<String, String> validateName(String name) {
    if (name == null || name.isBlank())
        return Validation.invalid("Name required");
    return Validation.valid(name);
}

Validation<String, Integer> validateAge(int age) {
    if (age < 0) return Validation.invalid("Age must be positive");
    if (age > 150) return Validation.invalid("Age unrealistic");
    return Validation.valid(age);
}

// Combine validations
Validation<String, User> result = Validation.combine(
    validateName(name),
    validateAge(age),
    User::new
);

// Handle result
if (result.isInvalid()) {
    result.getErrors().forEach(System.err::println);
}

vs Either | 与 Either 对比:

  • Either: Fails fast (first error only) - 快速失败(仅第一个错误)
  • Validation: Accumulates all errors - 累积所有错误

Security | 安全性:

  • Thread-safe: Yes (immutable) - 线程安全: 是 (不可变)
  • Null-safe: Allows null values - 空值安全: 允许 null 值
Since:
JDK 25, opencode-base-functional V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Interface
    Description
    static final class 
    Invalid - Represents a failed validation with accumulated errors Invalid - 表示失败的验证,包含累积的错误
    static final class 
    Valid - Represents a successful validation Valid - 表示成功的验证
  • Method Summary

    Modifier and Type
    Method
    Description
    <U> Validation<E,U>
    ap(Validation<E, Function<? super T, ? extends U>> vf)
    Apply a validated function to this validation (applicative) 将验证的函数应用于此验证(应用函子)
    static <E,T1,T2,T3,R>
    Validation<E,R>
    combine(Validation<E,T1> v1, Validation<E,T2> v2, Validation<E,T3> v3, TriFunction<T1,T2,T3,R> combiner)
    Combine three validations 组合三个验证
    static <E,T1,T2,R>
    Validation<E,R>
    combine(Validation<E,T1> v1, Validation<E,T2> v2, BiFunction<T1,T2,R> combiner)
    Combine two validations 组合两个验证
    <U> Validation<E,U>
    flatMap(Function<? super T, Validation<E,U>> mapper)
    FlatMap the value if Valid (monadic bind) 如果有效则扁平映射值(单子绑定)
    <R> R
    fold(Function<? super List<E>, ? extends R> ifInvalid, Function<? super T, ? extends R> ifValid)
    Fold this Validation by applying one of two functions 通过应用两个函数之一来折叠此 Validation
    Get the errors (empty list if Valid) 获取错误列表(如果有效则为空)
    default T
    getOrElseThrow(Function<? super List<E>, ? extends RuntimeException> exceptionMapper)
    Get the value if Valid, or throw a mapped exception if Invalid 如果有效则获取值,如果无效则抛出映射的异常
    Get the value if Valid 获取值(如果有效)
    static <E,T> Validation<E,T>
    invalid(E error)
    Create an Invalid result with single error 创建带单个错误的无效结果
    static <E,T> Validation<E,T>
    invalid(List<E> errors)
    Create an Invalid result with multiple errors 创建带多个错误的无效结果
    boolean
    Check if this is Invalid 检查是否无效
    boolean
    Check if this is Valid 检查是否有效
    <U> Validation<E,U>
    map(Function<? super T, ? extends U> mapper)
    Transform the value if Valid 如果有效则转换值
    <E2> Validation<E2,T>
    mapError(Function<? super E, ? extends E2> mapper)
    Transform the error type if Invalid 如果无效则转换错误类型
    default Validation<E,T>
    peek(Consumer<? super T> action)
    Execute an action on the value if Valid, then return this Validation 如果有效,对值执行操作,然后返回此 Validation
    static <E,T> Validation<E,List<T>>
    sequence(List<Validation<E,T>> validations)
    Sequence a list of validations 将验证列表序列化
    default Stream<T>
    Convert to Stream 转换为 Stream
    Convert to Either (errors as Left, value as Right) 转换为 Either(错误为 Left,值为 Right)
    default Option<T>
    Convert to Option monad 转换为 Option 单子
    default Try<T>
    Convert to Try monad 转换为 Try 单子
    static <E,T> Validation<E,T>
    valid(T value)
    Create a Valid result 创建有效结果
  • Method Details

    • valid

      static <E,T> Validation<E,T> valid(T value)
      Create a Valid result 创建有效结果
      Type Parameters:
      E - error type - 错误类型
      T - value type - 值类型
      Parameters:
      value - the value - 值
      Returns:
      Valid containing the value
    • invalid

      static <E,T> Validation<E,T> invalid(E error)
      Create an Invalid result with single error 创建带单个错误的无效结果
      Type Parameters:
      E - error type - 错误类型
      T - value type - 值类型
      Parameters:
      error - the error - 错误
      Returns:
      Invalid containing the error
    • invalid

      static <E,T> Validation<E,T> invalid(List<E> errors)
      Create an Invalid result with multiple errors 创建带多个错误的无效结果
      Type Parameters:
      E - error type - 错误类型
      T - value type - 值类型
      Parameters:
      errors - the errors (must not be null or contain null elements) - 错误列表(不能为 null 或包含 null 元素)
      Returns:
      Invalid containing the errors
    • isValid

      boolean isValid()
      Check if this is Valid 检查是否有效
      Returns:
      true if valid - 如果有效返回 true
    • isInvalid

      boolean isInvalid()
      Check if this is Invalid 检查是否无效
      Returns:
      true if invalid - 如果无效返回 true
    • getValue

      Optional<T> getValue()
      Get the value if Valid 获取值(如果有效)
      Returns:
      Optional containing value
    • getErrors

      List<E> getErrors()
      Get the errors (empty list if Valid) 获取错误列表(如果有效则为空)
      Returns:
      list of errors
    • map

      <U> Validation<E,U> map(Function<? super T, ? extends U> mapper)
      Transform the value if Valid 如果有效则转换值
      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - transformation function - 转换函数
      Returns:
      transformed Validation
    • flatMap

      <U> Validation<E,U> flatMap(Function<? super T, Validation<E,U>> mapper)
      FlatMap the value if Valid (monadic bind) 如果有效则扁平映射值(单子绑定)

      Note: Unlike ap(Validation), flatMap does NOT accumulate errors. If you need error accumulation, use ap(Validation) or combine(Validation, Validation, BiFunction).

      注意:与 ap(Validation) 不同,flatMap 不会累积错误。 如果需要累积错误,请使用 ap(Validation)combine(Validation, Validation, BiFunction)

      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - function returning Validation - 返回 Validation 的函数
      Returns:
      resulting Validation
    • ap

      <U> Validation<E,U> ap(Validation<E, Function<? super T, ? extends U>> vf)
      Apply a validated function to this validation (applicative) 将验证的函数应用于此验证(应用函子)

      This is the key operation for accumulating errors.

      这是累积错误的关键操作。

      Type Parameters:
      U - result type - 结果类型
      Parameters:
      vf - validation containing a function - 包含函数的验证
      Returns:
      combined Validation
    • fold

      <R> R fold(Function<? super List<E>, ? extends R> ifInvalid, Function<? super T, ? extends R> ifValid)
      Fold this Validation by applying one of two functions 通过应用两个函数之一来折叠此 Validation

      This is the catamorphism for Validation - handles both cases symmetrically.

      这是 Validation 的态射 - 对称地处理两种情况。

      Example | 示例:

      String result = validation.fold(
          errors -> "Errors: " + errors.size(),  // Invalid case
          value -> "Success: " + value           // Valid case
      );
      
      Type Parameters:
      R - result type - 结果类型
      Parameters:
      ifInvalid - function for Invalid case (receives error list) - Invalid 情况的函数(接收错误列表)
      ifValid - function for Valid case - Valid 情况的函数
      Returns:
      result of applying the appropriate function
    • mapError

      <E2> Validation<E2,T> mapError(Function<? super E, ? extends E2> mapper)
      Transform the error type if Invalid 如果无效则转换错误类型

      If this is Valid, returns itself (cast). If Invalid, transforms each error using the mapper function.

      如果有效,返回自身(类型转换)。如果无效,使用映射函数转换每个错误。

      Example | 示例:

      Validation<String, Integer> v = Validation.invalid("bad");
      Validation<Error, Integer> mapped = v.mapError(Error::new);
      
      Type Parameters:
      E2 - new error type - 新的错误类型
      Parameters:
      mapper - error transformation function - 错误转换函数
      Returns:
      Validation with transformed errors - 错误已转换的 Validation
    • peek

      default Validation<E,T> peek(Consumer<? super T> action)
      Execute an action on the value if Valid, then return this Validation 如果有效,对值执行操作,然后返回此 Validation

      This is useful for logging, debugging, or other side effects without breaking the fluent chain.

      这对于日志记录、调试或其他副作用非常有用,不会中断流式调用链。

      Example | 示例:

      Validation.valid("hello")
          .peek(v -> System.out.println("Value: " + v))
          .map(String::toUpperCase);
      
      Parameters:
      action - action to execute on the value - 对值执行的操作
      Returns:
      this Validation (unchanged) - 此 Validation(不变)
    • getOrElseThrow

      default T getOrElseThrow(Function<? super List<E>, ? extends RuntimeException> exceptionMapper)
      Get the value if Valid, or throw a mapped exception if Invalid 如果有效则获取值,如果无效则抛出映射的异常

      Example | 示例:

      String name = validation.getOrElseThrow(errors ->
          new IllegalArgumentException("Validation failed: " + errors));
      
      Parameters:
      exceptionMapper - function to create exception from errors - 从错误创建异常的函数
      Returns:
      the value if Valid - 如果有效则返回值
      Throws:
      RuntimeException - mapped exception if Invalid - 如果无效则抛出映射的异常
    • toTry

      default Try<T> toTry()
      Convert to Try monad 转换为 Try 单子

      Valid becomes Try.success(value). Invalid becomes Try.failure with an OpenFunctionalException containing the error messages.

      Valid 变为 Try.success(value)。Invalid 变为 Try.failure, 包含错误消息的 OpenFunctionalException。

      Returns:
      Try containing the value or failure - 包含值或失败的 Try
    • toOption

      default Option<T> toOption()
      Convert to Option monad 转换为 Option 单子

      Valid becomes Option.of(value). Invalid becomes Option.none().

      Valid 变为 Option.of(value)。Invalid 变为 Option.none()。

      Returns:
      Option containing the value or none - 包含值或空的 Option
    • stream

      default Stream<T> stream()
      Convert to Stream 转换为 Stream

      Valid becomes Stream.of(value). Invalid becomes Stream.empty().

      Valid 变为 Stream.of(value)。Invalid 变为 Stream.empty()。

      Returns:
      Stream containing the value or empty - 包含值或空的 Stream
    • toEither

      Either<List<E>,T> toEither()
      Convert to Either (errors as Left, value as Right) 转换为 Either(错误为 Left,值为 Right)
      Returns:
      Either
    • combine

      static <E,T1,T2,R> Validation<E,R> combine(Validation<E,T1> v1, Validation<E,T2> v2, BiFunction<T1,T2,R> combiner)
      Combine two validations 组合两个验证
      Type Parameters:
      E - error type - 错误类型
      T1 - first value type - 第一个值类型
      T2 - second value type - 第二个值类型
      R - result type - 结果类型
      Parameters:
      v1 - first validation - 第一个验证
      v2 - second validation - 第二个验证
      combiner - function to combine values - 组合值的函数
      Returns:
      combined Validation
    • combine

      static <E,T1,T2,T3,R> Validation<E,R> combine(Validation<E,T1> v1, Validation<E,T2> v2, Validation<E,T3> v3, TriFunction<T1,T2,T3,R> combiner)
      Combine three validations 组合三个验证
      Type Parameters:
      E - error type - 错误类型
      T1 - first value type - 第一个值类型
      T2 - second value type - 第二个值类型
      T3 - third value type - 第三个值类型
      R - result type - 结果类型
      Parameters:
      v1 - first validation - 第一个验证
      v2 - second validation - 第二个验证
      v3 - third validation - 第三个验证
      combiner - function to combine values - 组合值的函数
      Returns:
      combined Validation
    • sequence

      static <E,T> Validation<E,List<T>> sequence(List<Validation<E,T>> validations)
      Sequence a list of validations 将验证列表序列化
      Type Parameters:
      E - error type - 错误类型
      T - value type - 值类型
      Parameters:
      validations - list of validations - 验证列表
      Returns:
      Validation of list