eh3rrera / ocpj8-book

Study guide for the Oracle Certified Professional, Java SE 8 Programmer Exam (1Z0-809)
Other
129 stars 90 forks source link

Lambda expressions #68

Open Iurii-Mo opened 6 years ago

Iurii-Mo commented 6 years ago

Hi,

I really appreciate your book for OCPj8. You did a great work ! As for chapter 9 in the question

  1. A lambda expression can be used... A. As a method argument B. As a conditional expression in an if statement C. In a return statement D. In a throw statement

I'm not sure about "conditional expression in an if statement". It looks that we do can use lambdas in a conditional expression as

interface IBoo { boolean b(int z); } . . . IBoo ib = (int rr) -> rr == 0; if ( ib.b(0) ){ System.out.println("zero"); }

Or I did not get some idea in the text ? I can not find a difference in application of lambdas between return statement and if (condition).

Thanks, Iurii

eh3rrera commented 6 years ago

Hi Lurii,

Thank you for your kind words.

For me, something like this:

if ( ib.b(0) ) 

It's just a method call. You use a lambda in an assignment expression to create an implementation of the interface, but you're not using the lambda expression directly as the condition of the if statement.

I was referring to something like this:

if (  (int rr) -> rr == 0 )  

Which is wrong, a lambda expression doesn't evaluates to/return a boolean.

You can see a lambda expression as a shortcut for creating an anonymous class. Maybe a method from that anonymous class returns a boolean, but the class itself can't be used as the expression of an if statement.

But a lambda expression can be used in a return statement as long as the method returns the type the lambda expression represents:

public IBoo myMethod() {
   // ...
  return  (int rr) -> rr == 0;
}

By the way, in the answer explanation, I mention lambda expression can be used in "A ternary conditional expression". I don't mean the conditional expression, because it'd the same case. I mean this:

(CONDITION_THAT_RETURNS_BOOLEAN) ? LAMBDA_EXPRESSION : LAMBDA EXPRESSION

I think I'll change it to "A ternary conditional operator".

I hope I explained myself clearly. But what do you think? Should I remove this option from the question to avoid confusion? Or it is fine?

Thanks again!