像这样声明一个 IntConsumer:
int z = 0;
IntConsumer iConsumer = (a) -> z;
给出编译错误:“Void 方法无法返回值”。 好的
但是像这样:
int z = 0;
IntConsumer iConsumer = (a) -> Function.identity().apply(z);
何时 Function.identity().apply(z)
返回 Object
,这里没有编译错误。
不应该也给出编译错误吗?
最佳答案
z
是始终一个表达式。
Function.identity().apply(z)
是 an expression statement 。它可以用作表达式,因为它返回一个值。但只要该值被忽略,它就会被解释为语句。
An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded.
https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.8
IntConsumer#accept(int value)
期望返回 void
。如果是单行 lambda 主体,它必须是一条语句。
比较
// not allowed - expressions
IntConsumer a = (i) -> 2 + 2;
IntConsumer b = (i) -> true ? 1 : 0;
IntConsumer c = (i) -> (Function.identity().apply(i));
IntConsumer d = (i) -> (System.out.println(i));
IntConsumer e = (i) -> (new Object());
// allowed - expression statements
IntConsumer f = (i) -> Function.identity().apply(i);
IntConsumer g = (i) -> System.out.println(i);
IntConsumer h = (i) -> new Object();
关于java - IntConsumer 的编译器问题返回 Function.identity().apply(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346080/