Java 11 Local Variable Syntax for Lambda Parameters – Java 11兰姆达参数的局部变量语法

最后修改: 2018年 12月 15日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

The local variable syntax for lambda parameters is the only language feature introduced in Java 11. In this tutorial, we’ll explore and use this new feature.

lambda参数的局部变量语法是Java 11中唯一引入的语言特性。在本教程中,我们将探索和使用这个新特性。

2. Local Variable Syntax for Lambda Parameters

2.Lambda参数的局部变量语法

One of the key features introduced in Java 10 was local variable type inference. It allowed the use of var as the type of the local variable instead of the actual type. The compiler inferred the type based on the value assigned to the variable.

Java 10 中引入的关键功能之一是局部变量的类型推断。它允许使用var作为局部变量的类型而不是实际类型。编译器根据分配给该变量的值来推断类型。

However, we could not use this feature with lambda parameters. For example, consider the following lambda. Here we explicitly specify the types of the parameters:

然而,我们不能用lambda参数来使用这个功能。例如,考虑下面的lambda。这里我们明确指定了参数的类型。

(String s1, String s2) -> s1 + s2

We could skip the parameter types and rewrite the lambda as:

我们可以跳过参数类型,将lambda重写为。

(s1, s2) -> s1 + s2

Even Java 8 supported this. The logical extension to this in Java 10 would be:

甚至Java 8也支持这个。在Java 10中,这一点的逻辑延伸将是。

(var s1, var s2) -> s1 + s2

However, Java 10 did not support this.

然而,Java 10并不支持这一点。

Java 11 addresses this by supporting the above syntax. This makes the usage of var uniform in both local variables and lambda parameters.

Java 11通过支持上述语法来解决这个问题。这使得var在局部变量和lambda参数中的用法统一。

3. Benefit

3.效益

Why would we want to use var for lambda parameters when we could simply skip the types?

如果我们可以简单地跳过类型,为什么要为lambda参数使用var

One benefit of uniformity is that modifiers can be applied to local variables and lambda formals without losing brevity. For example, a common modifier is a type annotation:

统一性的一个好处是,修饰符可以应用于局部变量和lambda formals而不失简洁。例如,一个常见的修饰符是一个类型注释。

(@Nonnull var s1, @Nullable var s2) -> s1 + s2

We cannot use such annotations without specifying the types.

如果不指定类型,我们就不能使用这种注解。

4. Limitations

4.局限性

There are a few limitations of using var in lambda.

在lambda中使用var有一些限制。

For example, we cannot use var for some parameters and skip for others:

例如,我们不能对某些参数使用var,而对另一些参数使用跳过。

(var s1, s2) -> s1 + s2

Similarly, we cannot mix var with explicit types:

同样地,我们不能将var与显式类型混合。

(var s1, String s2) -> s1 + s2

Finally, even though we can skip the parentheses in single parameter lambda:

最后,尽管我们可以跳过单参数lambda中的括号。

s1 -> s1.toUpperCase()

we cannot skip them while using var:

我们不能在使用var时跳过它们。

var s1 -> s1.toUpperCase()

All of the above three usages will result in compilation error.

以上三种用法都会导致编译错误。

5. Conclusion

5.结论

In this quick article, we explored this cool new feature in Java 11 and saw how we can use local variable syntax for lambda parameters.

在这篇快速文章中,我们探讨了Java 11中这个很酷的新特性,并看到了我们如何为lambda参数使用局部变量语法。

As usual, the examples are available over on GitHub.

像往常一样,这些例子可以在GitHub上找到over