Win a 3 month subscription to Marco Behler Videos this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

forEach - Consumer?  RSS feed

 
Florian Jedamzik
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys;)

Lately more and more questions pop up...

For example I don't get why this Lines of Code actually compile:



why does line //x compile? I always thought forEach() expects
a Consumer, not a Function?

Then why does it work? Here, forEach() returns x+10;
and a Consumer never returns anything...so
I'm confused

Kind regards
Florian
 
Paweł Baczyński
Bartender
Posts: 2032
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This lambda doesn't return anything because it doesn't have a return statement.

Note that this is a lambda with braces. It does not use the shortened notation that would allow to skip the return statement.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37051
507
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This compiles too:


While there is a return value, it is ignored. So you have a statement that effectively doesn't do anything but is legal.

Just like this statement without lambdas is legal, but useless since the return value is ignored.


 
Florian Jedamzik
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah I see!;)

Thank you Jeanne and Pawel;)
 
A. Costa
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would you mind to explain a little bit better why the example of the dList.stream().forEach(x-> Double.valueOf(x)) compiles? I didn't grasp it.
As far as I know, if there is no braces and the "body" of the lamba expression is just one line, you will have as a return the body expression, so in this case Double.valueOf(x) should return a Double and the forEach shouldn't compile.

Could you explain it further?

Than you all! 
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37051
507
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The return type is ignored in this example because a Consumer doesn't return anything. So the compiler doesn't go looking for an implied return.

Which means this implicit one works:


But if you actually type return, it behaves as you would expect and fails to compile:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!