Lambda '特殊无效兼容性规则' - 语句表达式 [英] Lambda 'special void-compatibility rule' - statement expression

查看:14
本文介绍了Lambda '特殊无效兼容性规则' - 语句表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Java 8 实战.在第 3.5.2 节中有一段关于无效兼容性规则"的内容:

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

如果一个 lambda 表达式有一个语句表达式作为它的主体,它是兼容的带有返回 void 的函数描述符(提供参数列表也兼容).例如,以下两行都是合法,即使 List 的方法 add 返回一个布尔值而不是消费者上下文中的预期无效(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.

它们包括:

  • 方法调用
  • 作业
  • 递增/递减表达式
  • 类实例创建表达式

所以其他例子是:

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

<小时>

根据经验,形式为 x -> 的 lambda 表达式;expression 仅对 Consumer(或通常的 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 '特殊无效兼容性规则' - 语句表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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