Page 1 of 1

About Question enthuware.ocpjp.v8.2.1885 :

Posted: Mon Sep 14, 2020 1:42 pm
by Javier
Hi Paul!
I don´t understand why in some cases the Consumer function ignores the return type returned from the function and in other cases not.

Code: Select all

Consumer<Book> c = b->b.getId()+":"+b.getTitle();// this doesn´t compile, the type of the expression must be void, here is a String.

Code: Select all

Consumer<Book> c = b->b.getTitle();// but here compiles, the type of the expression is String as the previous one.
Paul could you explain me why is this behaviour, in one is ignoring the return type and in the other one not???
Thank you in advance

Re: About Question enthuware.ocpjp.v8.2.1885 :

Posted: Mon Sep 14, 2020 10:07 pm
by admin
b.getId()+":"+b.getTitle(); is an expression but not a valid statement, while b.getTitle(); is an expression as well as a valid statement.
It is like you can't just have, 2 + 3; in a method

{
...
2+3; //will not compile.
Math.random();//will compile.
...
}

This is explained in detail in Section 6.1.2 Expressions and Statements of Hanumant Deshmukh's OCP Java 11 Fundamentals book.

Re: About Question enthuware.ocpjp.v8.2.1885 :

Posted: Tue Sep 15, 2020 8:28 am
by Javier
Thank you Paul