Interface Try<T>
- Type Parameters:
T- value type - 值类型
- All Known Implementing Classes:
Try.Failure, Try.Success
Try Monad - Encapsulates computations that may fail
Try Monad - 封装可能失败的计算
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 TypeMethodDescriptionstatic <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 如果成功则转换为另一个 Tryget()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 如果成功则转换值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 的函数从失败恢复static <T> Try<T> success(T value) Create a Success with value 创建成功结果toEither()Convert to Either (Left=exception, Right=value) 转换为 Either(Left=异常,Right=值)Convert to Optional (empty if Failure) 转换为 Optional(失败时为空)
-
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
-