Prashant
Prashant

Reputation: 29

Invalid Lambda Expression

Why the below is not a valid Lambda Expression?

 (Integer i) -> return "Alan" + i;

I expect it to be valid, But it is actually Invalid , Please Explain

Upvotes: 1

Views: 10077

Answers (2)

Andrew
Andrew

Reputation: 49606

It would be a valid lambda expression if you got the syntax right.

Function<Integer, String> f1 = (Integer i) -> { return "Alan" + i; };
Function<Integer, String> f2 = (Integer i) -> "Alan" + i;
Function<Integer, String> f3 = (i) -> "Alan" + i;
Function<Integer, String> f4 = i -> "Alan" + i;

A lambda body is either an expression (1) or a block (2) (JLS-15.27.2).

(1)

returnexpression

return is never a part of an expression, it's a statement that controls execution flow (JLS-14.17).

(2)

To make it a block, braces are needed.

{ return expression; }

Upvotes: 5

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

A bit more context is needed, about how you're using it. But for starters, try removing the return:

(Integer i) -> "Alan" + i

Also, the Integer declaration might be redundant - but we really need to see what you're trying to accomplish, and the expected type of the lambda. Are you sure that the lambda is supposed to return a String?

Upvotes: 1

Related Questions