Java Reference
In-Depth Information
But you may be using an API that expects a functional interface such as Function<T, R> and
there's no option to create your own (you'll see in the next chapter that the Streams API makes
heavy use of the functional interfaces from table 3.2 ) . In this case you can explicitly catch the
checked exception:
Function<BufferedReader, String> f =
(BufferedReader b) -> {
try {
return b.readLine();
}
catch(IOException e) {
throw new RuntimeException(e);
}
};
You've now seen how to create lambdas and where and how to use them. Next, we explain some
more advanced details: how lambdas are type checked by the compiler and rules you should be
aware of, such as lambdas referencing local variables inside their body and void-compatible
lambdas. There's no need to fully understand the next section right away, and you may wish to
come back to it later and move on to section 3.6 about method references.
3.5. Type checking, type inference, and restrictions
When we first mentioned lambda expressions, we said that they let you generate an instance of a
functional interface. Nonetheless, a lambda expression itself doesn't contain the information
about which functional interface it's implementing. In order to have a more formal
understanding of lambda expressions, you should know what the actual type of a lambda is.
3.5.1. Type checking
The type of a lambda is deduced from the context in which the lambda is used. The type
expected for the lambda expression inside the context (for example, a method parameter that
it's passed to or a local variable that it's assigned to) is called the target type . Let's look at an
example to see what happens behind the scenes when you use a lambda expression. Figure 3.4
summarizes the type-checking process for the following code:
Search WWH ::




Custom Search