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
    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
    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 如果成功则转换值
    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 的函数从失败恢复
    static <T> Try<T>
    success(T value)
    Create a Success with value 创建成功结果
    Convert to Either (Left=exception, Right=value) 转换为 Either(Left=异常,Right=值)
    Convert to Optional (empty if Failure) 转换为 Optional(失败时为空)
  • 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