Java_Magazine_NovemberDecember_2018

(singke) #1

43


//java at present/


FilenameFilter xmlTargetFiles
= (var dir, var fileName) -> fileName.endsWith(".xml")
&& "target".equals(dir.getName());

What are the benefits of writing a couple of additional new characters?
There are two. First, since you can already use the var type inference syntax with local
variables as of Java 10, why not use var with lambda parameters as well? Doing so provides con-
sistency in the Java language. Second, this syntax enables you to use type annotations such as
@NonNull. These annotations can be helpful for documentation and also for type checking via the
Checker Framework. To find out more about how you can leverage such annotations generally to
catch more bugs in your application at compile time, see the Checker Framework’s website.
Here’s the lambda expression example using var and also annotated:

FilenameFilter xmlTargetFiles
= (@NonNull var dir, @NonNull var fileName)
-> fileName.endsWith(".xml")
&& "target".equals(dir.getName());

This syntax is not supported in implicitly typed parameters that don’t include var. Allowing
modifiers on a bare identifier would add significant complexity to the grammar of the Java
language, with little advantage.
Note that the introduction of the var syntax for lambda parameters does not allow you to
mix and match typed parameters and var parameters. For example, the following is forbidden
and results in a compile error:

// compile error
FilenameFilter xmlTargetFiles
= (var dir, String fileName) -> fileName.endsWith(".xml")
&& "target".equals(dir.getName());
Free download pdf