Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda 'special void-compatibility rule' - statement expression

Im reading Java 8 in Action. In section 3.5.2 there is a paragraph about 'void-compatibility rule':

If a lambda has a statement expression as its body, it’s compatible with a function descriptor that returns void (provided the parameter list is compatible too). For example, both of the following lines are legal even though the method add of a List returns a boolean and not void as expected in the Consumer context (T -> void):

// Predicate has a boolean return 
Predicate<String> p = s -> list.add(s); 
// Consumer has a void return 
Consumer<String> b = s -> list.add(s);

How would you describe 'statement expression' in general? I thought it was either statement or expression. Also this void-compatibility rule is not 100% clear to me, can you think of any other examples?

like image 473
jarosik Avatar asked Jan 05 '17 10:01

jarosik


1 Answers

The term “statement expression” or “expression statement” refers to expressions that are also allowed to be used as a statement. They are described in the Java Language Specification, §14.8. Expression Statements.

They include:

  • Method Invocations
  • Assignments
  • Increment/Decrement expressions
  • Class Instance Creation expressions

So other examples are:

Consumer<String> b = s -> counter++;
Function<String,Integer> f = s -> counter++;

or

Consumer<String> b = s -> new BigDecimal(s);
Function<String,BigDecimal> f = s -> new BigDecimal(s);

As a rule of thumb, a lambda expression of the form x -> expression is only legal for a Consumer (or void function type in general), if x -> { expression; } would be legal too.

like image 139
Holger Avatar answered Oct 06 '22 23:10

Holger