プログラミング言語Javaにおけるラムダ式は、その本体部に応じてvoid-compatible/value-compatible/その両方に区分される。
void-compatibleラムダ式はRunnableなどの戻り値を持たない(void)関数型インタフェース(functional interface)へ、value-compatibleラムダ式はIntSupplierなどの戻り値をもつ関数型インタフェースへと代入できる。
import java.util.function.IntSupplier; // void-compatible Runnable r1 = () -> { }; // OK IntSupplier s1 = () -> { }; // NG // value-compatible Runnable r2 = () -> { return 42; }; // NG IntSupplier s2 = () -> { return 42; }; // OK // void-compatible かつ value-compatible Runnable r3 = () -> { throw new NullPointerException(); }; // OK IntSupplier s3 = () -> { throw new NullPointerException(); }; // OK final boolean TRUE = true; Runnable r4 = () -> { while (TRUE); }; // OK IntSupplier s4 = () -> { while (TRUE); }; // OK
Java Language Specification, Java SE 8 Editionより一部引用。
The rules in this section define two technical terms:
- whether a statement is reachable
- whether a statement can complete normally
(snip)
The rules are as follows:
Chapter 14. Blocks and Statements, 14.21. Unreachable Statements
- (snip)
- A
whilestatement can complete normally iff at least one of the following istrue:
- The
whilestatement is reachable and the condition expression is not a constant expression (§15.28) with valuetrue.- There is a reachable
breakstatement that exits thewhilestatement.- (snip)
- A
break,continue,return, orthrowstatement cannot complete normally.- (snip)
A block lambda body is void-compatible if every
returnstatement in the block has the formreturn;.A block lambda body is value-compatible if it cannot complete normally (§14.21) and every
returnstatement in the block has the formreturn Expression;.(snip)
Note that the void/value-compatible definition is not a strictly structural property: "can complete normally" depends on the values of constant expressions, and these may include names that reference constant variables.
Chapter 15. Expressions, 15.27.2. Lambda Body
関連URL