Java 11:Lambda 参数的本地变量语法 - 应用程序 [英] Java 11: Local-Variable Syntax for Lambda Parameters - applications

查看:21
本文介绍了Java 11:Lambda 参数的本地变量语法 - 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇Java-11 一般而言,但特别是 JEP:323 计划添加 var 对 Lambda 操作变量的声明.

I am curious about Java-11 in general, but specifically JEP:323 which plans to add the var declaration to Lambda operation variables.

很好地讨论了此功能背后的动机此处.请考虑文章中的以下引用:

The motivation behind this feature is discussed nicely here. Consider the following quote from the article:

// #1 - Legal
ITest divide = (@ATest var x, final var y) ->  x / y;
/* #2 Modifiers on Old-Style implicit paramaters => Illegal */
ITest divide = (@ATest x, final y) ->  x / y;

final 修饰符的用法对我来说很清楚,并且符合不变性最佳实践.

The usage of the final modifier is clear to me and is in line with immutability best practices.

但是,我不确定注释.能够注释 lambda 隐式参数的最大好处是什么?

However, I am not sure about the annotations. What is the great benefit of being able to annotate a lambda implicit parameter?

您能否提供一个在 lambda 操作变量上使用注释的实际有益示例?不是意见问题,而是作为使用此功能时更具可读性或效率的代码的实际示例.

Can you provide a de-facto, beneficial example of using annotations on a lambda operation variable? Not as a matter of opinion, but as an actual example of code which is more readable or efficient when using this feature.

推荐答案

能够注释 lambda 隐式参数的最大好处是什么?

What is the great benefit of being able to annotate a lambda implicit parameter?

lambda 语句中注释的使用应该类似于非 lambda 语句上的任何其他属性.这可能是为了利用:

The usage of annotations within lambda statement should be similar to any other attribute on a non-lambda statement. This could be to make use of:

  • 在运行时反射并推断有关注释对象的一些信息.
  • 也在编译时描述行为,例如生成的源代码或其他工具提示

JEP-323 中所述的用例em> 本身(重申自己不确定这是否是您所期待的)-

A use case stated in the JEP-323 itself(reiterating myself of not being sure if that's what you're looking forward to) -

(@Nonnull var x, @Nullable var y) -> x.process(y)

库可以使用注释来确定对 xy 的值检查.在那一点上,您知道 x.process(y) 肯定不会抛出 NullPointerException 甚至在没有对 x 进行显式空检查的情况下,现在是与任何其他显式注释的非 lambda 参数相同.

where the annotations can be used by the libraries to determine a value check over x and y. In that, you know x.process(y) can certainly not throw a NullPointerException without even placing an explicit null check for x now which is same as any other explicitly annotated non-lambda parameter.

值得注意的是,这是引入允许 var 作为隐式类型 lambda 表达式的形式参数的一致性的好处之一.

Notably, this is one of the benefits of bringing in the uniformity of allowing var for the formal parameters of an implicitly typed lambda expression.

这篇关于Java 11:Lambda 参数的本地变量语法 - 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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