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

Rann Lifshitz :

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.

Naman :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=432003&siteId=1