Why does this Java 8 lambda fail to compile?

JavaLambdaCompiler ErrorsJava 8Void

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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:

Solution 2 - Java

Basicly, new String("hi") is an executable piece of code that actually does something (it creates a new String and then returns it). The returned value can be ignored and new String("hi") can still be used in void-return lambda to create a new String.

However, "hi" is just a constant that doesn't do anything on it's own. The only reasonable thing to do with it in lambda body is to return it. But the lambda method would have to have return type String or Object, but it returns void, hence the String cannot be casted to void error.

Solution 3 - Java

The first case is ok because you are invoking a "special" method (a constructor) and you are no actually taking the created object. Just to make it more clear, I'll put the optional braces in your lambdas:

takeBiConsumer((String s1, String s2) -> {new String("hi");}); // OK
takeBiConsumer((String s1, String s2) -> {"hi"}); // Error

And more clear, I'll translate that to the older notation:

takeBiConsumer(new BiConsumer<String, String>(String s1, String s2) {
	public void accept(String s, String s2) {
		new String("hi"); // OK
	}
});

takeBiConsumer(new BiConsumer<String, String>(String s1, String s2) {
	public void accept(String s, String s2) {
		"hi"; // Here, the compiler will attempt to add a "return"
              // keyword before the "hi", but then it will fail
              // with "compiler error ... bla bla ...
              //  java.lang.String cannot be converted to void"
	}
});

In the first case you are executing a constructor, but you are NOT returning the created object, in the second case you are attempting to return a String value, but your method in your interface BiConsumer returns void, hence the compiler error.

Solution 4 - Java

The JLS specify that

> If the function type's result is void, the lambda body is either a > statement expression (§14.8) or a void-compatible block.

Now let's see that in detail,

Since your takeBiConsumer method is of void type, the lambda receiving new String("hi") will interpret it as a block like

{
    new String("hi");
}

which is valid in a void, hence the first case compile.

However, in the case where the lambda is -> "hi", a block such as

{
    "hi";
}

is not valid syntax in java. Therefore the only thing to do with "hi" is to try and return it.

{
    return "hi";
}

which is not valid in a void and explain 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 a String, -> "hi" will be valid as it will simply try to directly return the string.


Note that at first I tought the error was caused by the lambda being in a wrong invocation context, so I'll share this possibility with the community :

JLS 15.27

> It is a compile-time error if a lambda expression occurs in a program > in someplace other than an assignment context (§5.2), an invocation > context (§5.3), or a casting context (§5.5).

However in our case, we are in an invocation context which is correct.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRagView Question on Stackoverflow
Solution 1 - JavaassyliasView Answer on Stackoverflow
Solution 2 - JavakajacxView Answer on Stackoverflow
Solution 3 - JavamorganoView Answer on Stackoverflow
Solution 4 - JavaJean-François SavardView Answer on Stackoverflow