Java Reference
In-Depth Information
The second example is also valid. Indeed, the return type of the method fetch is
Callable<String>. Callable<String> essentially defines a method with the signature () -> String
when T is replaced with String. Because the lambda () -> "Tricky example ;-)" has the signature ()
-> String, the lambda can be used in this context.
The third example is invalid because the lambda expression (Apple a) -> a.getWeight() has the
signature (Apple) -> Integer, which is different than the signature of the method test defined in
Predicate<Apple>: (Apple) -> boolean.
What about @FunctionalInterface?
If you explore the new Java API, you'll notice that functional interfaces are annotated with
@FunctionalInterface (we show an extensive list in section 3.4 , where we explore functional
interfaces in depth). This annotation is used to indicate that the interface is intended to be a
functional interface. The compiler will return a meaningful error if you define an interface using
the @FunctionalInterface annotation and it isn't a functional interface. For example, an error
message could be “Multiple non-overriding abstract methods found in interface Foo” to indicate
that more than one abstract method is available. Note that the @FunctionalInterface annotation
isn't mandatory, but it's good practice to use it when an interface is designed for that purpose.
You can think of it like the @Override notation to indicate that a method is overridden.
3.3. Putting lambdas into practice: the execute around pattern
Let's look at an example of how lambdas, together with behavior parameterization, can be used
in practice to make your code more flexible and concise. A recurrent pattern in resource
processing (for example, dealing with files or databases) is to open a resource, do some
processing on it, and then close the resource. The setup and cleanup phases are always similar
and surround the important code doing the processing. This is called the execute around pattern,
as illustrated in figure 3.2 . For example, in the following code, the highlighted lines show the
boilerplate code required to read one line from a file (note also that you use Java 7's
try-with-resources statement, which already simplifies the code, because you don't have to close
the resource explicitly):
Search WWH ::




Custom Search