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 中,demo
和 demo2
都只能列印 0
。但這並不是更加一致。Java 方法與重構和類的使用一致 - 頂部程式碼中的 return
,下面的程式碼表現相同:
void demo3() {
threeTimes(new MyIntConsumer());
}
class MyIntConsumer implements IntConsumer {
public void accept(int i) {
System.out.println(i);
return;
}
}
因此,Java return
與類方法和重構更加一致,但對於 for
和 while
內建函式更少,這些仍然是特殊的。
因此,以下兩個在 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()
。