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

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

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

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 中所述的用例

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天全站免登陆