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.
A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression. Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression.
Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.
A lambda expression is characterized by the following syntax. Following are the important characteristics of a lambda expression. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With