Class OpenMatch

java.lang.Object
cloud.opencode.base.functional.pattern.OpenMatch

public final class OpenMatch extends Object
OpenMatch - Pattern matching entry point OpenMatch - 模式匹配入口

Provides a fluent API for pattern matching that complements JDK 25's native pattern matching with additional features.

提供流式 API 用于模式匹配,补充 JDK 25 原生模式匹配的附加功能。

Features | 主要功能:

  • Type matching (caseOf) - 类型匹配
  • Predicate matching (when) - 谓词匹配
  • Value equality matching (whenEquals) - 值相等匹配
  • Record deconstruction (caseRecord) - Record 解构
  • Sealed type matching (caseSealed) - 密封类型匹配

Usage Examples | 使用示例:

// Basic type matching
String result = OpenMatch.of(value)
    .caseOf(String.class, s -> "String: " + s)
    .caseOf(Integer.class, n -> "Number: " + n)
    .caseOf(List.class, l -> "List: " + l.size())
    .orElse(o -> "Unknown");

// Predicate matching
String desc = OpenMatch.of(number)
    .when(n -> n < 0, n -> "Negative")
    .when(n -> n == 0, n -> "Zero")
    .when(n -> n > 0, n -> "Positive")
    .orElseThrow();

// Value matching
String day = OpenMatch.of(dayOfWeek)
    .whenEquals(1, d -> "Monday")
    .whenEquals(2, d -> "Tuesday")
    .orElse(d -> "Other");

// Use JDK 25 native pattern matching for sealed types
double area = switch (shape) {
    case Circle(var r) -> Math.PI * r * r;
    case Rectangle(var w, var h) -> w * h;
};

Security | 安全性:

  • Thread-safe: Yes (matcher is mutable but typically used locally)
  • Null-safe: Handles null values - 空值安全: 处理 null 值

Performance | 性能特性:

  • Time complexity: O(k) where k is the number of cases evaluated before first match - 时间复杂度: O(k),k 为首次匹配前评估的分支数
  • Space complexity: O(1) per Matcher instance - 空间复杂度: O(1) 每个 Matcher 实例
Since:
JDK 25, opencode-base-functional V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • of

      public static <T> OpenMatch.Matcher<T> of(T value)
      Start pattern matching on a value 开始对值进行模式匹配
      Type Parameters:
      T - value type - 值类型
      Parameters:
      value - value to match - 要匹配的值
      Returns:
      Matcher for fluent API