Java Reference
In-Depth Information
The lambda expression passed into overloadedMethod is compatible with both a normal
Predicate and the IntPredicate . There are method overloads for each of these options
defined within this code block. In this case, javac will fail to compile the example, com-
plaining that the lambda expression is an ambiguous method call: IntPredicate doesn't ex-
tend any Predicate , so the compiler isn't able to infer that it's more specific.
The way to fix these situations is to cast the lambda expression to either IntPredicate or
Predicate<Integer> , depending upon which behavior you want to call. Of course, if
you've designed the library yourself, you might conclude that this is a code smell and you
should start renaming your overloaded methods.
In summary, the parameter types of a lambda are inferred from the target type , and the infer-
ence follows these rules:
▪ If there is a single possible target type, the lambda expression infers the type from the
corresponding argument on the functional interface.
▪ If there are several possible target types, the most specific type is inferred.
▪ If there are several possible target types and there is no most specific type, you must
manually provide a type.
@FunctionalInterface
Although I talked about the criteria for what a functional interface actually is back in
Chapter 2 , I haven't yet mentioned the @FunctionalInterface annotation. This is an an-
notation that should be applied to any interface that is intended to be used as a functional in-
terface.
What does that really mean? Well, there are some interfaces in Java that have only a single
method but aren't normally meant to be implemented by lambda expressions. For example,
they might assume that the object has internal state and be interfaces with a single method
only coincidentally. A couple of good examples are java.lang.Comparable and
java.io.Closeable .
If a class is Comparable , it means there is a defined order between instances, such as alpha-
betical order for strings. You don't normally think about functions themselves as being com-
parable objects because they lack fields and state, and if there are no fields and no state, what
is there to sensibly compare?
Search WWH ::




Custom Search