0

I am new learner for Java 8 lambda . I found a statement in a book (Java 8 for Really Impatient ), saying , "It is illegal for a lambda expression to return a value in some branches but not in others. For example, (int x) -> { if (x>= 0) return 1; } is invalid."

Can anyone explain this ? Please provide some examples.

Thanks in advance.

asked Mar 22, 2017 at 21:08
5
  • 6
    I don't understand your confusion. You already have an example with an explanation. It's invalid because only one of two branches returns a value. Commented Mar 22, 2017 at 21:10
  • 3
    No matter if you write a standard method or something like the lambda expression above, the code needs to have some defined outcome. In your example, for a negative input (x) the expression is not returning anything - which is not allowed. Commented Mar 22, 2017 at 21:12
  • 3
    This book should be retitled Java 8 for Really patient. Java 8 is out for 3 years now ;-) Commented Mar 22, 2017 at 21:13
  • @C-Otto , Thanks for ur reply . Got it !! . Somehow missed the context Commented Mar 22, 2017 at 21:28
  • @SotiriosDelimanolis , Thanks for ur reply . Commented Mar 22, 2017 at 21:29

2 Answers 2

4

I don't get it where you don't get it. Will this compile for example?

 static int test(int x) {
 if(x >= 0) {
 return 1;
 }
 }

Same goes for the lambda expression.

answered Mar 22, 2017 at 21:12
Sign up to request clarification or add additional context in comments.

Comments

0

you have to ensure no matter "if" statement is true or false, there is always a return value or there is always not.

In your case:

illegal: (int x) -> { if (x >= 0) return 1; }
legal: (int x) -> { if (x >= 0) return 1; else return 0;}

This is because this method below is illegal

int lambda (int x){
 if (x >= 0)
 return 1;
}
answered Aug 17, 2020 at 19:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.