Interface Try<T>

Type Parameters:
T - value type - 值类型
All Known Implementing Classes:
Try.Failure, Try.Success

public sealed interface Try<T> permits Try.Success<T>, Try.Failure<T>
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 Classes
    Modifier and Type
    Interface
    Description
    static final class 
    Failure - Represents a failed computation Failure - 表示失败的计算
    static final class 
    Success - Represents a successful computation Success - 表示成功的计算
  • Method Summary

    Modifier and Type
    Method
    Description
    default Try<T>
    Execute action regardless of success or failure, similar to try-finally semantics.
    default boolean
    contains(T value)
    Check if this is a Success containing a value equal to the given value.
    default boolean
    exists(Predicate<? super T> predicate)
    Check if this is a Success and the predicate matches the contained value.
    static <T> Try<T>
    failure(Throwable throwable)
    Create a Failure with exception 创建失败结果
    filter(Predicate<? super T> predicate)
    Filter the value with a predicate 使用谓词过滤值
    <U> Try<U>
    flatMap(Function<? super T, Try<U>> mapper)
    Transform the value to another Try if Success 如果成功则转换为另一个 Try
    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.
    get()
    Get the value, throws if failure 获取值,失败时抛出异常
    Get the exception if this is a Failure 获取异常(如果失败)
    getOrElse(T defaultValue)
    Get value or default if Failure 获取值或默认值(如果失败)
    boolean
    Check if this is a Failure 检查是否失败
    boolean
    Check if this is a Success 检查是否成功
    <U> Try<U>
    map(Function<? super T, ? extends U> mapper)
    Transform the value if Success 如果成功则转换值
    default Try<T>
    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 失败时执行操作
    onSuccess(Consumer<? super T> action)
    Execute action on success 成功时执行操作
    orElse(Try<T> other)
    Return this or other Try if Failure 返回本 Try 或其他 Try(如果失败)
    peek(Consumer<? super T> action)
    Execute action on the value if Success 如果成功则对值执行操作
    Recover from Failure with a function 使用函数从失败恢复
    Recover from Failure with a function returning Try 使用返回 Try 的函数从失败恢复
    default Stream<T>
    Convert to Stream.
    static <T> Try<T>
    success(T value)
    Create a Success with value 创建成功结果
    Convert to Either (Left=exception, Right=value) 转换为 Either(Left=异常,Right=值)
    default Option<T>
    Convert to Option.
    Convert to Optional (empty if Failure) 转换为 Optional(失败时为空)
    Convert to Validation.
  • Method Details

    • of

      static <T> Try<T> of(CheckedSupplier<T> supplier)
      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

      static <T> Try<T> success(T value)
      Create a Success with value 创建成功结果
      Type Parameters:
      T - value type - 值类型
      Parameters:
      value - result value - 结果值
      Returns:
      Success containing the value
    • failure

      static <T> Try<T> failure(Throwable throwable)
      Create a Failure with exception 创建失败结果
      Type Parameters:
      T - value type - 值类型
      Parameters:
      throwable - the exception - 异常
      Returns:
      Failure containing the exception
    • 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

      Optional<Throwable> getCause()
      Get the exception if this is a Failure 获取异常(如果失败)
      Returns:
      Optional containing the exception, empty if Success
    • map

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

      <U> Try<U> flatMap(Function<? super T, Try<U>> mapper)
      Transform the value to another Try if Success 如果成功则转换为另一个 Try
      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - transformation function returning Try - 返回 Try 的转换函数
      Returns:
      resulting Try
    • filter

      Try<T> filter(Predicate<? super T> predicate)
      Filter the value with a predicate 使用谓词过滤值
      Parameters:
      predicate - filter condition - 过滤条件
      Returns:
      filtered Try (Failure if predicate not satisfied)
    • getOrElse

      T getOrElse(T defaultValue)
      Get value or default if Failure 获取值或默认值(如果失败)
      Parameters:
      defaultValue - default value to use on failure - 失败时使用的默认值
      Returns:
      value or default
    • orElse

      Try<T> orElse(Try<T> other)
      Return this or other Try if Failure 返回本 Try 或其他 Try(如果失败)
      Parameters:
      other - alternative Try - 备选 Try
      Returns:
      this if Success, other if Failure
    • recover

      Try<T> recover(Function<Throwable, T> recovery)
      Recover from Failure with a function 使用函数从失败恢复
      Parameters:
      recovery - recovery function - 恢复函数
      Returns:
      recovered Try
    • recoverWith

      Try<T> recoverWith(Function<Throwable, Try<T>> recovery)
      Recover from Failure with a function returning Try 使用返回 Try 的函数从失败恢复
      Parameters:
      recovery - recovery function returning Try - 返回 Try 的恢复函数
      Returns:
      recovered Try
    • toOptional

      Optional<T> toOptional()
      Convert to Optional (empty if Failure) 转换为 Optional(失败时为空)
      Returns:
      Optional containing value or empty
    • toEither

      Either<Throwable, T> toEither()
      Convert to Either (Left=exception, Right=value) 转换为 Either(Left=异常,Right=值)
      Returns:
      Either with exception or value
    • peek

      Try<T> peek(Consumer<? super T> action)
      Execute action on the value if Success 如果成功则对值执行操作
      Parameters:
      action - action to execute - 要执行的操作
      Returns:
      this Try for chaining
    • onFailure

      Try<T> onFailure(Consumer<Throwable> action)
      Execute action on failure 失败时执行操作
      Parameters:
      action - action to execute on exception - 对异常执行的操作
      Returns:
      this Try for chaining
    • onSuccess

      Try<T> onSuccess(Consumer<? super T> action)
      Execute action on success 成功时执行操作
      Parameters:
      action - action to execute on value - 对值执行的操作
      Returns:
      this Try for chaining
    • andFinally

      default Try<T> andFinally(Runnable action)
      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

      default Try<T> mapFailure(Function<Throwable, ? extends Throwable> mapper)
      Transform the exception if this is a Failure. If Success, return this unchanged. 如果是 Failure 则转换异常。如果是 Success 则原样返回。

      If the mapper itself throws, returns a new Try.Failure wrapping 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

      default Option<T> toOption()
      Convert to Option. Success maps to Option.of(value), Failure maps to Option.none(). 转换为 Option。Success 映射为 Option.of(value),Failure 映射为 Option.none()。
      Returns:
      Option containing the value or none | 包含值的 Option 或 none
    • toValidation

      default Validation<Throwable, T> 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

      default Stream<T> stream()
      Convert to Stream. Success maps to Stream.of(value), Failure maps to Stream.empty(). 转换为 Stream。Success 映射为 Stream.of(value),Failure 映射为 Stream.empty()。
      Returns:
      Stream containing the value or empty | 包含值的 Stream 或空 Stream
    • contains

      default boolean contains(T value)
      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

      default boolean exists(Predicate<? super T> predicate)
      Check if this is a Success and the predicate matches the contained value. 检查是否为 Success 且谓词匹配包含的值。
      Parameters:
      predicate - the predicate to test - 要测试的谓词
      Returns:
      true if Success and predicate matches | 如果是 Success 且谓词匹配返回 true