Reputation: 351
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.
Upvotes: 0
Views: 517
Reputation: 55
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;
}
Upvotes: 0
Reputation: 120998
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.
Upvotes: 4