JLS indicates that
If the result of the function type is invalid, the lambda body is either an expression of an expression (§14.8) or a block compatible with void.
Now let's see that in detail,
Since your takeBiConsumer method is of type void, the receiving lambda new String("hi") will interpret it as a block, for example
{ new String("hi"); }
which is valid in the void, so the first case compiles.
However, in the case where lambda -> "hi" , a block like
{ "hi"; }
Invalid syntax in java. Therefore, the only thing you need to do with hello is to try and get it back.
{ return "hi"; }
which is invalid in the void and explains the error message
incompatible types: bad return type in lambda expression java.lang.String cannot be converted to void
For a better understanding, note that if you change the type of takeBiConsumer to String, it will be valid -> "hi" because it will just try to directly return the string.
Please note that at first I made a mistake that the error was caused by the fact that lambda is in the wrong call context, so I shared this opportunity with the community:
JLS 15.27
This is a compile-time error if the lambda expression appears in a program in a place other than the destination context (§5.2), the call context (§5.3), or the casting context (§5.5).
However, in our case, we are in the context of a call that is correct.
Jean-François Savard Mar 25 '15 at 17:11 2015-03-25 17:11
source share