Java 11: Local-Variable Syntax for Lambda Parameters - applications

ε祈祈猫儿з 提交于 2020-01-22 10:46:06

问题


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.

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

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.


回答1:


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

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:

  • reflection and infer some information about the annotated object at runtime.
  • also at compile time to depict behaviors such as generated source code or other hints for tools

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)

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.

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.



来源:https://stackoverflow.com/questions/50225672/java-11-local-variable-syntax-for-lambda-parameters-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!