Page 1 of 1

About Question enthuware.ocpjp.v11.2.3076 :

Posted: Sun Dec 20, 2020 7:57 am
by menelaus
Hi,
I know that a consumer does not return something. So it is normal for this code not to compile.

Code: Select all

Consumer<Book> c = b->b.getId()+":"+b.getTitle();
On the other hand this code compiles. Even it is returning a value.

Code: Select all

Consumer<Book> c = b->b.getId();
What is the difference between these two codes?

Re: About Question enthuware.ocpjp.v11.2.3076 :

Posted: Sun Dec 20, 2020 11:11 pm
by admin
For this you need to understand two things:
1. The difference between a statement and an expression. b.getId()+":"+b.getTitle(); is a valid expression but not a valid statement.
and b.getId(); is a valid expression as well as a valid statement. (Check out section 6.1.2 of https://amzn.to/2PucBeT for details.)

2. You can check the validity of a lambda expression by converting it into an anonymous class (the compiler does not actually do this but it is a valid approach). Like this:

Code: Select all

Consumer<Book> c = new Consumer<Book>(){
     public void consume(Book b){
      b.getId()+":"+b.getTitle(); //code from lambda body goes here
     }
  };

and 

Consumer<Book> c = new Consumer<Book>(){
     public void consume(Book b){
      b.getId(); //code from lambda body goes here
     }
  };
You can now easily see why the first one will not compile even though both expression return a value and which can be ignored by the JVM. A method body must be composed of valid statements (which may or may not be valid expressions) but b.getId()+":"+b.getTitle(); is not a valid statement.

Re: About Question enthuware.ocpjp.v11.2.3076 :

Posted: Mon Dec 21, 2020 5:47 am
by menelaus
Thanks