Interface Validation<E,T>
- Type Parameters:
E- error type - 错误类型T- value type - 值类型
- All Known Implementing Classes:
Validation.Invalid, Validation.Valid
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 ClassesModifier and TypeInterfaceDescriptionstatic final classInvalid - Represents a failed validation with accumulated errors Invalid - 表示失败的验证,包含累积的错误static final classValid - Represents a successful validation Valid - 表示成功的验证 -
Method Summary
Modifier and TypeMethodDescription<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> RFold this Validation by applying one of two functions 通过应用两个函数之一来折叠此 ValidationGet the errors (empty list if Valid) 获取错误列表(如果有效则为空)default TgetOrElseThrow(Function<? super List<E>, ? extends RuntimeException> exceptionMapper) Get the value if Valid, or throw a mapped exception if Invalid 如果有效则获取值,如果无效则抛出映射的异常getValue()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> Create an Invalid result with multiple errors 创建带多个错误的无效结果booleanCheck if this is Invalid 检查是否无效booleanisValid()Check if this is Valid 检查是否有效<U> Validation<E, U> Transform the value if Valid 如果有效则转换值<E2> Validation<E2, T> Transform the error type if Invalid 如果无效则转换错误类型default Validation<E, T> Execute an action on the value if Valid, then return this Validation 如果有效,对值执行操作,然后返回此 Validationstatic <E,T> Validation <E, List<T>> sequence(List<Validation<E, T>> validations) Sequence a list of validations 将验证列表序列化stream()Convert to Stream 转换为 StreamtoEither()Convert to Either (errors as Left, value as Right) 转换为 Either(错误为 Left,值为 Right)toOption()Convert to Option monad 转换为 Option 单子toTry()Convert to Try monad 转换为 Try 单子static <E,T> Validation <E, T> valid(T value) Create a Valid result 创建有效结果
-
Method Details
-
valid
Create a Valid result 创建有效结果- Type Parameters:
E- error type - 错误类型T- value type - 值类型- Parameters:
value- the value - 值- Returns:
- Valid containing the value
-
invalid
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
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
-
getErrors
-
map
Transform the value if Valid 如果有效则转换值- Type Parameters:
U- result type - 结果类型- Parameters:
mapper- transformation function - 转换函数- Returns:
- transformed Validation
-
flatMap
FlatMap the value if Valid (monadic bind) 如果有效则扁平映射值(单子绑定)Note: Unlike
ap(Validation), flatMap does NOT accumulate errors. If you need error accumulation, useap(Validation)orcombine(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
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 通过应用两个函数之一来折叠此 ValidationThis 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
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
Execute an action on the value if Valid, then return this Validation 如果有效,对值执行操作,然后返回此 ValidationThis 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
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
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
-
stream
-
toEither
-
combine
static <E,T1, Validation<E,T2, R> 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, Validation<E,T2, T3, R> 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
Sequence a list of validations 将验证列表序列化- Type Parameters:
E- error type - 错误类型T- value type - 值类型- Parameters:
validations- list of validations - 验证列表- Returns:
- Validation of list
-