Class For

java.lang.Object
cloud.opencode.base.functional.monad.For

public final class For extends Object
For - For-comprehension for simplified flatMap operations For - 简化 flatMap 操作的 For 表达式

Provides a cleaner syntax for combining multiple monadic values, avoiding deeply nested flatMap calls. Similar to Scala's for-comprehension or Vavr's For.

提供更简洁的语法来组合多个 Monad 值,避免深层嵌套的 flatMap 调用。 类似于 Scala 的 for 表达式或 Vavr 的 For。

The Problem | 问题:

// Deeply nested flatMap is hard to read
optA.flatMap(a ->
    optB.flatMap(b ->
        optC.flatMap(c ->
            optD.map(d ->
                combine(a, b, c, d)
            )
        )
    )
);

The Solution | 解决方案:

// Clean for-comprehension style
For.of(optA)
   .and(optB)
   .and(optC)
   .and(optD)
   .yield((a, b, c, d) -> combine(a, b, c, d));

Features | 主要功能:

  • Supports Option, Try, Either, List, Sequence - 支持 Option、Try、Either、List、Sequence
  • Type-safe with generics - 泛型类型安全
  • Up to 8 values - 最多支持 8 个值
  • Clean, readable syntax - 简洁可读的语法

Usage Examples | 使用示例:

// With Option
Option<String> result = For.of(getName())
    .and(getAge())
    .yield((name, age) -> name + " is " + age);

// With Try
Try<Integer> result = For.of(parseNumber(a))
    .and(parseNumber(b))
    .yield((x, y) -> x + y);

// With Iterable (List)
List<String> pairs = For.of(List.of("a", "b"))
    .and(List.of(1, 2))
    .yield((s, n) -> s + n)
    .toList();
// ["a1", "a2", "b1", "b2"]

// Complex example with guards
For.of(users)
    .and(roles)
    .filter((user, role) -> user.canHaveRole(role))
    .yield((user, role) -> new Assignment(user, role));

Security | 安全性:

  • Thread-safe: Implementation-dependent - 线程安全: 取决于实现
  • Null-safe: No - 空值安全: 否
Since:
JDK 25, opencode-base-functional V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • of

      public static <T> For.OptionFor1<T> of(Option<T> option)
      Start a for-comprehension with an Option. 使用 Option 开始 for 表达式。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      option - the option - 选项
      Returns:
      for1 builder - for1 构建器
    • of

      public static <T> For.TryFor1<T> of(Try<T> t)
      Start a for-comprehension with a Try. 使用 Try 开始 for 表达式。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      t - the try - Try 实例
      Returns:
      for1 builder - for1 构建器
    • of

      public static <T> For.IterableFor1<T> of(Iterable<T> iterable)
      Start a for-comprehension with an Iterable. 使用 Iterable 开始 for 表达式。
      Type Parameters:
      T - element type - 元素类型
      Parameters:
      iterable - the iterable - 可迭代对象
      Returns:
      for1 builder - for1 构建器
    • of

      public static <T> For.SequenceFor1<T> of(Sequence<T> sequence)
      Start a for-comprehension with a Sequence. 使用 Sequence 开始 for 表达式。
      Type Parameters:
      T - element type - 元素类型
      Parameters:
      sequence - the sequence - 序列
      Returns:
      for1 builder - for1 构建器