本文介绍了Lambda'特殊的void-compatibility rule' - 语句表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Java 8 in Action。在3.5.2节中有一个关于'void-compatibility rule'的段落:

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



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

您如何描述'语句表达'?我以为这是陈述或表达。此虚空兼容性规则对我来说也不是100%清楚,你能想到其他任何例子吗?

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?

推荐答案

这个词语句表达式或表达式语句是指也允许用作语句的表达式。它们在Java语言规范中描述,。

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.

它们包括


  • 方法调用

  • 作业

  • 增量/减量表达式

  • 类实例创建表达式

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

所以其他例子是

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

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






根据经验,lambda表达式为表格 x - >表达式仅对消费者(或一般的 void 函数类型)合法,如果 x - > {表达; } 也是合法的。


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.

这篇关于Lambda'特殊的void-compatibility rule' - 语句表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:12