Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Java 8 lambda fail to compile?

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.

like image 971
Rag Avatar asked Mar 25 '15 17:03

Rag


People also ask

What is the key reason for including lambda expression in JDK 8?

Introduction. Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .

Does Java 8 have lambda?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

What happens when lambda throws exception?

Rules for Lambda ExpressionA lambda expression cannot throw any checked exception until its corresponding functional interface declares a throws clause. An exception thrown by any lambda expression can be of the same type or sub-type of the exception declared in the throws clause of its functional interface.

What is the use of the project lambda in Java 8?

What is project lambda: Project lambda is the project to enable lambda expressions in java language syntax. Lambda expressions are major syntax in functional programming languages like lisp. Groovy would be the closest relative of java that has support for lambda expressions, also known as closures.


1 Answers

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:

  • A constructor invocation is a statement expression so it compiles.
  • A string literal isn't a statement expression and is not void compatible (cf. the examples in 15.27.2) so it does not compile.
like image 126
assylias Avatar answered Oct 25 '22 01:10

assylias