Java Reference
In-Depth Information
3.5.3. Type inference
You can simplify your code one step further. The Java compiler deduces what functional
interface to associate with a lambda expression from its surrounding context (the target type),
meaning it can also deduce an appropriate signature for the lambda because the function
descriptor is available through the target type. The benefit is that the compiler has access to the
types of the parameters of a lambda expression, and they can be omitted in the lambda syntax.
In other words, the Java compiler infers the types of the parameters of a lambda as shown
here: [ 3 ]
3 Note that when a lambda has just one parameter whose type is inferred, the parentheses
surrounding the parameter name can also be omitted.
The benefits of code readability are more noticeable with lambda expressions that have several
parameters. For example, here's how to create a Comparator object:
Note that sometimes it's more readable to include the types explicitly and sometimes more
readable to exclude them. There's no rule for which way is better; developers must make their
own choices about what makes their code more readable.
3.5.4. Using local variables
All the lambda expressions we've shown so far used only their arguments inside their body. But
lambda expressions are also allowed to use free variables (variables that aren't the parameters
and defined in an outer scope) just like anonymous classes can. They're called capturing
lambdas . For example, the following lambda captures the variable portNumber:
int portNumber = 1337;
Runnable r = () -> System.out.println(portNumber);
Nonetheless, there's a small twist: there are some restrictions on what you can do with these
variables. Lambdas are allowed to capture (that is, to reference in their bodies) instance
variables and static variables without restrictions. But local variables have to be explicitly
 
Search WWH ::




Custom Search