Lambda'特殊的void-compatibility rule' - 语句表达式 [英] Lambda 'special void-compatibility rule' - statement expression

查看:268
本文介绍了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':


如果一个lambda有一个语句表达式作为它的主体,它与函数描述符兼容
,返回void(假设参数
list也兼容)。例如,以下两行都是
合法,即使List的方法添加返回布尔值而不是消费者上下文中预期的
void(T - > void):

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);

您如何描述'语句表达'?我以为这是陈述或表达。此虚空兼容性规则对我来说也不是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语言规范中描述,§14.8。表达式陈述

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' - 语句表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆