Java Reference
In-Depth Information
Lambda expressions can also be used to represent methods that take more than one argu-
ment, as in . At this juncture, it's worth reflecting on how to read this lambda expression.
This line of code doesn't add up two numbers; it creates a function that adds together two
numbers. The variable called add that's a BinaryOperator<Long> isn't the result of adding
up two numbers; it is code that adds together two numbers.
So far, all the types for lambda expression parameters have been inferred for us by the com-
piler. This is great, but it's sometimes good to have the option of explicitly writing the type,
and when you do that you need to surround the arguments to the lambda expression with par-
entheses. The parentheses are also necessary if you've got multiple arguments. This ap-
proach is demonstrated in .
NOTE
The target type of a lambda expression is the type of the context in which the lambda ex-
pression appears—for example, a local variable that it's assigned to or a method paramet-
er that it gets passed into.
What is implicit in all these examples is that a lambda expression's type is context depend-
ent. It gets inferred by the compiler. This target typing isn't entirely new, either. As shown in
Example 2-4 , the types of array initializers in Java have always been inferred from their con-
texts. Another familiar example is null . You can know what the type of null is only once
you actually assign it to something.
Example 2-4. The righthand side doesn't specify its type; it is inferred from the context
final
final String [] array = { "hello" , "world" };
Using Values
When you've used anonymous inner classes in the past, you've probably encountered a situ-
ation in which you wanted to use a variable from the surrounding method. In order to do so,
you had to make the variable final , as demonstrated in Example 2-5 . Making a variable fi-
nal means that you can't reassign to that variable. It also means that whenever you're using
a final variable, you know you're using a specific value that has been assigned to the vari-
able.
 
 
Search WWH ::




Custom Search