Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lambda expressions #68

Open
Iurii-Mo opened this issue Aug 2, 2018 · 1 comment
Open

Lambda expressions #68

Iurii-Mo opened this issue Aug 2, 2018 · 1 comment

Comments

@Iurii-Mo
Copy link

Iurii-Mo commented Aug 2, 2018

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
Copy link
Owner

eh3rrera commented Aug 2, 2018

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants