In the Java programming language, a method invocation expression is a Statement Statement , a construct that can appear in both places where an expression is required or where an instruction is required.
Therefore, you can use the simplified form of the expression param -> expression for the case of using e -> System.out.println("hi") , even if the method returns void . Since the expected signature function here is <T extends Event> T -> void , your lambda expression containing one call to the void method is valid for this context.
Things change when you try to use an Expression expression in a different context where the expression is required. Compare JLS ยง15.1 :
An expression does not mean anything if and only if it is a method call (ยง15.12) that calls a method that does not return a value, that is, a method declared void (ยง8.4). Such an expression can only be used as an expression (ยง14.8), because any other context in which the expression can be displayed requires an expression to denote something.
Applying this rule formally, even just putting curly braces around it, as in (System.out.println("hi")) , is invalid because it is a compound expression trying to use the method call of the declared void method in a context where "real expression "(return value).
And so the lambda expression using an invalid expression like in mi.setOnAction(e -> (System.out.println("hi"))); can not is also valid. The message is a bit misleading. It seems that the compiler focuses on the fact that the form expression ( whatever ) is an expression without an expression and therefore cannot be valid in the void context. However, reporting the original error placing the void method call in parentheses would be more useful.
The rule that you cannot put ( โฆ ) around calling the void method has not changed, so the error was older than the compiler accepting this syntax, which seems to be fixed.
Holger Jun 10 '14 at 17:27 2014-06-10 17:27
source share