yohhoyの日記

技術的メモをしていきたい日記

{void,value,both}-compatibleラムダ式

プログラミング言語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:

  • (snip)
  • A while statement can complete normally iff at least one of the following is true:
    • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.
    • There is a reachable break statement that exits the while statement.
  • (snip)
  • A break, continue, return, or throw statement cannot complete normally.
  • (snip)
Chapter 14. Blocks and Statements, 14.21. Unreachable Statements

A block lambda body is void-compatible if every return statement in the block has the form return;.

A block lambda body is value-compatible if it cannot complete normally (§14.21) and every return statement in the block has the form return 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