In the first line you provided a valid Consumer
which takes an argument int a
. This is what Stream.forEach
expects. The fact, that the consumer will additionaly return a value doesn't matter. The returned value will not be evaluated, it will be discarded.
The second line contains a statement which returns a boolean
. As this statement has a return value, it doesn't comply with the method of Consumer
which takes an argument but is declared void
. Thus this gives the compile-time error: Void methods cannot return a value
JLS 15.27.2 says:
A block lambda body is void-compatible if every return statement in
the block has the form return;.
Thus the method returns without an explicit return value.
Regarding the return statement JLS 14.17. says:
A return statement with no Expression must be contained in one of the
following, or a compile-time error occurs:
- A method that is declared, using the keyword void, not to return a
value (§8.4.5)
Applying this to the second line results in the following code:
Stream.of(1, 2, 3, 4).forEach(a -> { a.equals(1); return; });
Further notes:
By returning the value of equals
in the second line this statement doesn't become a Function
. It's still just a statement.
An exception will not be thrown as an exception can only be thrown on runtime. Since the code doesn't compile, it cannot be executed. As specified in the JLS a compile-time error is issued.