Interface Option<T>

Type Parameters:
T - value type - 值类型
All Known Implementing Classes:
Option.None, Option.Some

public sealed interface Option<T> permits Option.Some<T>, Option.None<T>
Option Monad - Enhanced Optional with more functional operations Option Monad - 增强的 Optional,提供更多函数式操作

A sealed type representing an optional value - either Option.Some containing a value or Option.None representing absence.

一个密封类型表示可选值 - Option.Some 包含值或 Option.None 表示缺失。

Features | 主要功能:

  • Sealed type with Some/None - 带 Some/None 的密封类型
  • Monadic operations (map, flatMap, filter) - Monad 操作
  • Interoperability with Optional - 与 Optional 互操作
  • Pattern matching friendly - 模式匹配友好

Usage Examples | 使用示例:

// Creating Options
Option<String> some = Option.some("value");
Option<String> none = Option.none();
Option<String> fromNullable = Option.of(nullableValue);

// Chained operations
String result = Option.of(user)
    .map(User::getAddress)
    .flatMap(addr -> Option.of(addr.getCity()))
    .map(String::toUpperCase)
    .getOrElse("UNKNOWN");

// Pattern matching with JDK 25
String desc = switch (option) {
    case Option.Some(var v) -> "Has: " + v;
    case Option.None() -> "Empty";
};

vs java.util.Optional | 与 Optional 对比:

  • Sealed type enables pattern matching - 密封类型支持模式匹配
  • Some/None explicitly typed - Some/None 显式类型
  • Richer API - 更丰富的 API

Security | 安全性:

  • Thread-safe: Yes (immutable) - 线程安全: 是 (不可变)
  • Null-safe: None for null - 空值安全: null 返回 None
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 
    None - Represents absence of value None - 表示值缺失
    static final record 
    Some - Contains a value Some - 包含值
  • Method Summary

    Modifier and Type
    Method
    Description
    default boolean
    contains(T value)
    Check if this is a Some containing a value equal to the given value.
    default boolean
    exists(Predicate<? super T> predicate)
    Check if this is a Some and the predicate matches the contained value.
    filter(Predicate<? super T> predicate)
    Filter the value with predicate 使用谓词过滤值
    <U> Option<U>
    flatMap(Function<? super T, Option<U>> mapper)
    Transform to another Option if Some 如果是 Some 则转换为另一个 Option
    <R> R
    fold(Supplier<? extends R> ifNone, Function<? super T, ? extends R> ifSome)
    Fold this Option by applying one of two functions 通过应用两个函数之一来折叠此 Option
    default boolean
    forAll(Predicate<? super T> predicate)
    Check if the predicate holds for all values.
    static <T> Option<T>
    fromOptional(Optional<T> optional)
    Create Option from Optional 从 Optional 创建 Option
    get()
    Get the value, throws if None 获取值,如果是 None 则抛出异常
    getOrElse(Supplier<? extends T> supplier)
    Get value or compute default if None 获取值或计算默认值(如果是 None)
    getOrElse(T defaultValue)
    Get value or default if None 获取值或默认值(如果是 None)
    boolean
    Check if this is None 检查是否为 None
    boolean
    Check if this is Some 检查是否为 Some
    <U> Option<U>
    map(Function<? super T, ? extends U> mapper)
    Transform the value if Some 如果是 Some 则转换值
    static <T> Option<T>
    Create a None 创建 None
    static <T> Option<T>
    of(T value)
    Create Option from nullable value 从可空值创建 Option
    onNone(Runnable action)
    Execute action if None 如果是 None 则执行操作
    orElse(Option<T> other)
    Return this or other Option if None 返回本 Option 或其他 Option(如果是 None)
    orElse(Supplier<Option<T>> supplier)
    Return this or computed Option if None 返回本 Option 或计算的 Option(如果是 None)
    peek(Consumer<? super T> action)
    Execute action if Some 如果是 Some 则执行操作
    static <T> Option<T>
    some(T value)
    Create a Some with value 创建包含值的 Some
    default Stream<T>
    Convert to Stream.
    <L> Either<L,T>
    toEither(L left)
    Convert to Either (None becomes Left) 转换为 Either(None 变为 Left)
    Convert to Optional 转换为 Optional
    default Try<T>
    toTry(Supplier<? extends Throwable> exceptionSupplier)
    Convert to Try.
    default <E> Validation<E,T>
    toValidation(E error)
    Convert to Validation.
    static <T> Option<T>
    when(boolean condition, Supplier<T> supplier)
    Create Option from supplier if condition is true 如果条件为真则从供应商创建 Option
    default <U,R> Option<R>
    zip(Option<U> other, BiFunction<? super T, ? super U, ? extends R> zipper)
    Zip this Option with another using a combining function.
  • Method Details

    • some

      static <T> Option<T> some(T value)
      Create a Some with value 创建包含值的 Some
      Type Parameters:
      T - value type - 值类型
      Parameters:
      value - the value (must not be null) - 值(不能为 null)
      Returns:
      Some containing the value
      Throws:
      NullPointerException - if value is null
    • none

      static <T> Option<T> none()
      Create a None 创建 None
      Type Parameters:
      T - value type - 值类型
      Returns:
      None instance
    • of

      static <T> Option<T> of(T value)
      Create Option from nullable value 从可空值创建 Option
      Type Parameters:
      T - value type - 值类型
      Parameters:
      value - nullable value - 可空值
      Returns:
      Some if value not null, None otherwise
    • fromOptional

      static <T> Option<T> fromOptional(Optional<T> optional)
      Create Option from Optional 从 Optional 创建 Option
      Type Parameters:
      T - value type - 值类型
      Parameters:
      optional - the optional - Optional
      Returns:
      corresponding Option
    • when

      static <T> Option<T> when(boolean condition, Supplier<T> supplier)
      Create Option from supplier if condition is true 如果条件为真则从供应商创建 Option
      Type Parameters:
      T - value type - 值类型
      Parameters:
      condition - condition - 条件
      supplier - value supplier - 值供应商
      Returns:
      Some if condition true and value not null, None otherwise
    • isSome

      boolean isSome()
      Check if this is Some 检查是否为 Some
      Returns:
      true if Some - 如果是 Some 返回 true
    • isNone

      boolean isNone()
      Check if this is None 检查是否为 None
      Returns:
      true if None - 如果是 None 返回 true
    • get

      T get()
      Get the value, throws if None 获取值,如果是 None 则抛出异常
      Returns:
      the value - 值
      Throws:
      NoSuchElementException - if None
    • map

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

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

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

      <R> R fold(Supplier<? extends R> ifNone, Function<? super T, ? extends R> ifSome)
      Fold this Option by applying one of two functions 通过应用两个函数之一来折叠此 Option

      This is the catamorphism for Option - handles both cases symmetrically.

      这是 Option 的态射 - 对称地处理两种情况。

      Example | 示例:

      String result = option.fold(
          () -> "No value",          // None case
          value -> "Got: " + value    // Some case
      );
      
      Type Parameters:
      R - result type - 结果类型
      Parameters:
      ifNone - function for None case - None 情况的函数
      ifSome - function for Some case - Some 情况的函数
      Returns:
      result of applying the appropriate function
    • getOrElse

      T getOrElse(T defaultValue)
      Get value or default if None 获取值或默认值(如果是 None)
      Parameters:
      defaultValue - default value - 默认值
      Returns:
      value or default
    • getOrElse

      T getOrElse(Supplier<? extends T> supplier)
      Get value or compute default if None 获取值或计算默认值(如果是 None)
      Parameters:
      supplier - default value supplier - 默认值供应商
      Returns:
      value or computed default
    • orElse

      Option<T> orElse(Option<T> other)
      Return this or other Option if None 返回本 Option 或其他 Option(如果是 None)
      Parameters:
      other - alternative Option - 备选 Option
      Returns:
      this if Some, other if None
    • orElse

      Option<T> orElse(Supplier<Option<T>> supplier)
      Return this or computed Option if None 返回本 Option 或计算的 Option(如果是 None)
      Parameters:
      supplier - Option supplier - Option 供应商
      Returns:
      this if Some, computed if None
    • toOptional

      Optional<T> toOptional()
      Convert to Optional 转换为 Optional
      Returns:
      Optional
    • toEither

      <L> Either<L,T> toEither(L left)
      Convert to Either (None becomes Left) 转换为 Either(None 变为 Left)
      Type Parameters:
      L - left type - 左类型
      Parameters:
      left - value for Left if None - None 时的 Left 值
      Returns:
      Either
    • peek

      Option<T> peek(Consumer<? super T> action)
      Execute action if Some 如果是 Some 则执行操作
      Parameters:
      action - action to execute - 要执行的操作
      Returns:
      this Option for chaining
    • onNone

      Option<T> onNone(Runnable action)
      Execute action if None 如果是 None 则执行操作
      Parameters:
      action - action to execute - 要执行的操作
      Returns:
      this Option for chaining
    • contains

      default boolean contains(T value)
      Check if this is a Some containing a value equal to the given value. 检查是否为包含与给定值相等的值的 Some。
      Parameters:
      value - the value to compare - 要比较的值
      Returns:
      true if Some and value equals contained value | 如果是 Some 且值相等返回 true
    • exists

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

      default boolean forAll(Predicate<? super T> predicate)
      Check if the predicate holds for all values. Returns true for None (vacuously true). 检查谓词是否对所有值成立。对于 None 返回 true(空集满足)。
      Parameters:
      predicate - the predicate to test - 要测试的谓词
      Returns:
      true if None or predicate matches | 如果是 None 或谓词匹配返回 true
    • toTry

      default Try<T> toTry(Supplier<? extends Throwable> exceptionSupplier)
      Convert to Try. Some maps to Try.success(value), None maps to Try.failure with the supplied exception. 转换为 Try。Some 映射为 Try.success(value),None 映射为带有提供异常的 Try.failure。
      Parameters:
      exceptionSupplier - supplier for the exception when None - None 时异常的供应商
      Returns:
      Try containing the value or failure | 包含值的 Try 或失败
    • stream

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

      default <U,R> Option<R> zip(Option<U> other, BiFunction<? super T, ? super U, ? extends R> zipper)
      Zip this Option with another using a combining function. Both must be Some for the result to be Some. 使用组合函数将此 Option 与另一个 Option 进行组合。 两者都必须是 Some 才能得到 Some 结果。
      Type Parameters:
      U - the other value type - 另一个值类型
      R - the result type - 结果类型
      Parameters:
      other - the other Option - 另一个 Option
      zipper - the combining function - 组合函数
      Returns:
      Some with combined value if both are Some, None otherwise | 如果两者都是 Some 返回组合值的 Some,否则返回 None
    • toValidation

      default <E> Validation<E,T> toValidation(E error)
      Convert to Validation. Some maps to Validation.valid(value), None maps to Validation.invalid(error). 转换为 Validation。Some 映射为 Validation.valid(value),None 映射为 Validation.invalid(error)。
      Type Parameters:
      E - error type - 错误类型
      Parameters:
      error - the error value for None case - None 情况下的错误值
      Returns:
      Validation containing the value or error | 包含值或错误的 Validation