Interface Try<T>
- Type Parameters:
T- value type - 值类型
- All Known Implementing Classes:
Try.Failure, Try.Success
A sealed type representing the result of a computation that may either
succeed with a value (Try.Success) or fail with an exception (Try.Failure).
一个密封类型,表示可能成功(带值)或失败(带异常)的计算结果。
Features | 主要功能:
- Exception handling without try-catch - 无需 try-catch 的异常处理
- Monadic operations (map, flatMap, filter) - Monad 操作
- Recovery mechanisms - 恢复机制
- Conversion to Optional/Either - 转换为 Optional/Either
- Side effect handling - 副作用处理
Usage Examples | 使用示例:
// Basic usage
Try<Integer> result = Try.of(() -> Integer.parseInt("123"));
// Chained operations
String message = Try.of(() -> readFile("config.json"))
.map(this::parseJson)
.map(config -> config.get("name"))
.map(name -> "Hello, " + name)
.getOrElse("Hello, Guest");
// Error recovery
User user = Try.of(() -> userService.findById(id))
.recover(e -> defaultUser)
.get();
// Side effects
Try.of(() -> sendEmail(to, subject, body))
.onSuccess(r -> log.info("Email sent"))
.onFailure(e -> log.error("Failed", e));
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 classFailure - Represents a failed computation Failure - 表示失败的计算static final classSuccess - Represents a successful computation Success - 表示成功的计算 -
Method Summary
Modifier and TypeMethodDescriptionandFinally(Runnable action) Execute action regardless of success or failure, similar to try-finally semantics.default booleanCheck if this is a Success containing a value equal to the given value.default booleanCheck if this is a Success and the predicate matches the contained value.static <T> Try<T> Create a Failure with exception 创建失败结果Filter the value with a predicate 使用谓词过滤值<U> Try<U> Transform the value to another Try if Success 如果成功则转换为另一个 Trydefault <R> Rfold(Function<Throwable, ? extends R> failureMapper, Function<? super T, ? extends R> successMapper) Fold this Try into a single value by applying one of two functions.get()Get the value, throws if failure 获取值,失败时抛出异常getCause()Get the exception if this is a Failure 获取异常(如果失败)Get value or default if Failure 获取值或默认值(如果失败)booleanCheck if this is a Failure 检查是否失败booleanCheck if this is a Success 检查是否成功<U> Try<U> Transform the value if Success 如果成功则转换值mapFailure(Function<Throwable, ? extends Throwable> mapper) Transform the exception if this is a Failure.static <T> Try<T> of(CheckedSupplier<T> supplier) Execute a computation that may fail 执行可能失败的计算Execute action on failure 失败时执行操作Execute action on success 成功时执行操作Return this or other Try if Failure 返回本 Try 或其他 Try(如果失败)Execute action on the value if Success 如果成功则对值执行操作Recover from Failure with a function 使用函数从失败恢复recoverWith(Function<Throwable, Try<T>> recovery) Recover from Failure with a function returning Try 使用返回 Try 的函数从失败恢复stream()Convert to Stream.static <T> Try<T> success(T value) Create a Success with value 创建成功结果toEither()Convert to Either (Left=exception, Right=value) 转换为 Either(Left=异常,Right=值)toOption()Convert to Option.Convert to Optional (empty if Failure) 转换为 Optional(失败时为空)default Validation<Throwable, T> Convert to Validation.
-
Method Details
-
of
Execute a computation that may fail 执行可能失败的计算- Type Parameters:
T- result type - 结果类型- Parameters:
supplier- computation to execute - 要执行的计算- Returns:
- Success with result or Failure with exception
-
success
Create a Success with value 创建成功结果- Type Parameters:
T- value type - 值类型- Parameters:
value- result value - 结果值- Returns:
- Success containing the value
-
failure
-
isSuccess
boolean isSuccess()Check if this is a Success 检查是否成功- Returns:
- true if success - 如果成功返回 true
-
isFailure
boolean isFailure()Check if this is a Failure 检查是否失败- Returns:
- true if failure - 如果失败返回 true
-
get
T get()Get the value, throws if failure 获取值,失败时抛出异常- Returns:
- the value - 值
- Throws:
OpenFunctionalException- if this is a Failure
-
getCause
-
map
-
flatMap
-
filter
-
getOrElse
-
orElse
-
recover
-
recoverWith
-
toOptional
-
toEither
-
peek
-
onFailure
-
onSuccess
-
andFinally
Execute action regardless of success or failure, similar to try-finally semantics. 无论成功或失败都执行操作,类似 try-finally 语义。If the action succeeds, returns this Try unchanged. If the action throws and this is a Success, returns a new Failure with the action's exception. If the action throws and this is already a Failure, the action's exception is added as a suppressed exception to the original cause, and the original Failure is returned.
如果操作成功,原样返回此 Try。 如果操作抛出异常且当前为 Success,返回包含该异常的新 Failure。 如果操作抛出异常且当前已为 Failure,操作异常作为 suppressed 异常添加到原始异常中, 并返回原始 Failure。
- Parameters:
action- the action to execute - 要执行的操作- Returns:
- this Try if action succeeds, or Failure if action throws | 如果操作成功返回此 Try,否则返回 Failure
-
mapFailure
Transform the exception if this is a Failure. If Success, return this unchanged. 如果是 Failure 则转换异常。如果是 Success 则原样返回。If the mapper itself throws, returns a new
Try.Failurewrapping the mapper's exception, with the original cause added as a suppressed exception (mirroring try-with-resources semantics).如果 mapper 本身抛出异常,返回包装 mapper 异常的新
Try.Failure, 原始 cause 作为 suppressed 异常附加(类似 try-with-resources 语义)。- Parameters:
mapper- function to transform the exception - 转换异常的函数- Returns:
- Try with mapped exception if Failure, or this if Success | 如果是 Failure 返回转换后的异常,否则返回此 Try
-
fold
default <R> R fold(Function<Throwable, ? extends R> failureMapper, Function<? super T, ? extends R> successMapper) Fold this Try into a single value by applying one of two functions. 通过应用两个函数之一将此 Try 折叠为单个值。- Type Parameters:
R- result type - 结果类型- Parameters:
failureMapper- function for Failure case - Failure 情况的函数successMapper- function for Success case - Success 情况的函数- Returns:
- result of applying the appropriate function | 应用相应函数的结果
-
toOption
-
toValidation
Convert to Validation. Success maps to Validation.valid(value), Failure maps to Validation.invalid(cause). 转换为 Validation。Success 映射为 Validation.valid(value),Failure 映射为 Validation.invalid(cause)。- Returns:
- Validation containing the value or the cause | 包含值或异常原因的 Validation
-
stream
-
contains
Check if this is a Success containing a value equal to the given value. 检查是否为包含与给定值相等的值的 Success。- Parameters:
value- the value to compare - 要比较的值- Returns:
- true if Success and value equals contained value | 如果是 Success 且值相等返回 true
-
exists
-