The following Java code fails to compile:
@FunctionalInterface
private interface BiConsumer<A, B> {
void accept(A a, B b);
}
private static void takeBiConsumer(BiConsumer<String, String> bc) { }
public static void main(String[] args) {
takeBiConsumer((String s1, String s2) -> new String("hi")); // OK
takeBiConsumer((String s1, String s2) -> "hi"); // Error
}
The compiler reports:
Error:(31, 58) java: incompatible types: bad return type in lambda expression
java.lang.String cannot be converted to void
The weird thing is that the line marked "OK" compiles fine, but the line marked "Error" fails. They seem essentially identical.
Your lambda needs to be congruent with BiConsumer<String, String>
. If you refer to JLS #15.27.3 (Type of a Lambda):
A lambda expression is congruent with a function type if all of the following are true:
- [...]
- If the function type's result is void, the lambda body is either a statement expression (§14.8) or a void-compatible block.
So the lambda must either be a statement expression or a void compatible block: