return 只返回 lambda 而不是外部方法

return 方法仅从 lambda 返回,而不是外部方法。

请注意,这与 Scala 和 Kotlin 不同

void threeTimes(IntConsumer r) {
  for (int i = 0; i < 3; i++) {
    r.accept(i);
  }
}

void demo() {
  threeTimes(i -> {
    System.out.println(i);
    return; // Return from lambda to threeTimes only!
  });
}

这可能会在尝试编写自己的语言结构时导致意外行为,因为在内置结构(如 for 循环)中,return 的行为有所不同:

void demo2() {
  for (int i = 0; i < 3; i++) {
    System.out.println(i);
    return; // Return from 'demo2' entirely
  }
}

在 Scala 和 Kotlin 中,demodemo2 都只能打印 0。但这并不是更加一致。Java 方法与重构和类的使用一致 - 顶部代码中的 return,下面的代码表现相同:

void demo3() {
  threeTimes(new MyIntConsumer());
}

class MyIntConsumer implements IntConsumer {
  public void accept(int i) {
    System.out.println(i);
    return;
  }
}

因此,Java return 与类方法和重构更加一致,但对于 forwhile 内置函数更少,这些仍然是特殊的。

因此,以下两个在 Java 中是等效的:

IntStream.range(1, 4)
    .map(x -> x * x)
    .forEach(System.out::println);
IntStream.range(1, 4)
    .map(x -> { return x * x; })
    .forEach(System.out::println);

此外,在 Java 中使用 try-with-resources 是安全的:

class Resource implements AutoCloseable {
  public void close() { System.out.println("close()"); }
}

void executeAround(Consumer<Resource> f) {
  try (Resource r = new Resource()) {
    System.out.print("before ");
    f.accept(r);
    System.out.print("after ");
  }
}

void demo4() {
  executeAround(r -> {
    System.out.print("accept() ");
    return; // Does not return from demo4, but frees the resource.
  });
}

将打印 before accept() after close()。在 Scala 和 Kotlin 语义中,try-with-resources 不会被关闭,但它只会打印 before accept()