Java Reference
In-Depth Information
that the declared type is a functional interface. If the annotation @FunctionalInterface is used on a non-functional
interface or other types such as classes, a compile-time error occurs. If you do not use the annotation
@FunctionalInterface on an interface with one abstract method, the interface is still a functional interface and it can
be the target type for lambda expressions. Using this annotation gives you an additional assurance from the compiler.
The presence of the annotation also protects you from inadvertently changing a functional interface into a
non-functional interface, as the compiler will catch it.
The following declaration for an Operations interface will not compile, as the interface declaration uses the
@FunctionalInterface annotation and it is not a functional interface (defines two abstract methods):
@FunctionalInterface
public interface Operations {
double add(double n1, double n2);
double subtract(double n1, double n2);
}
To compile the Operations interface, either remove one of the two abstract methods or remove the
@FunctionalInterface annotation.
The following declaration for a Test class will not compile, as @FunctionalInterface cannot be used on a type
other than a functional interface:
@FunctionalInterface
public class Test {
// Code goes here
}
Generic Functional Interface
It is allowed for a functional interface to have type parameters. That is, a functional interface can be generic.
An example of a generic functional parameter is the Comparator interface with one type parameter T .
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
A functional interface may have a generic abstract method. That is, the abstract method may declare type
parameters. The following is an example of a non-generic functional interface called Processor whose abstract
method process() is generic:
@FunctionalInterface
public interface Processor {
<T> void process(T[] list);
}
A lambda expression cannot declare type parameters, and therefore, it cannot have a target type whose abstract
method is generic. For example, you cannot represent the Processor interface using a lambda expression. In such
cases, you need to use a method reference, which I discuss in the next section, or an anonymous class.
Let's have a short example of a generic functional interface and instantiating it using lambda expressions.
Listing 5-8 shows the code for a functional interface named Mapper .
 
Search WWH ::




Custom Search