Java Reference
In-Depth Information
Return Context : A lambda expression may appear in a return statement inside a method, as its
target type is the declared return type of the method. For example,
return LambdaExpression;
Cast Context : A lambda expression may be used if it is preceded by a cast. The type specified in
the cast is its target type. For example,
(Joiner) LambdaExpression;
Functional Interfaces
A functional interface is simply an interface that has exactly one abstract method. The following types of methods in
an interface do not count for defining a functional interface:
Default methods
Static methods
Object class
Note that an interface may have more than one abstract method, and can still be a functional interface if all but
one of them is a redeclaration of the methods in the Object class. Consider the declaration of the Comparator class
that is in the java.util package, as shown:
Public methods inherited from the
package java.util;
@FunctionalInterface
public interface Comparator<T> {
// An abstract method declared in the interface
int compare(T o1, T o2);
// Re-declaration of the equals() method in the Object class
boolean equals(Object obj);
/* Many static and default methods that are not shown here. */
}
The Comparator interface contains two abstract methods: compare() and equals() . The equals() method in the
Comparator interface is a redeclaration of the equals() method of the Object class, and therefore it does not count
against the one abstract method requirement for it to be a functional interface. The Comparator interface contains
several default and static method that are not shown here.
A lambda expression is used to represent an unnamed function as used in functional programming. A functional
interface represents one type of functionality/operation in terms of its lone abstract method. This commonality is the
reason why the target type of a lambda expression is always a functional interface.
Using the @FunctionalInterface Annotation
The declaration of a functional interface may optionally be annotated with the annotation @FunctionalInterface ,
which is in the java.lang package. So far, all functional interfaces declared in this chapter, such as Adder and Joiner ,
have been annotated with @FunctionalInterface . The presence of this annotation tells the compiler to make sure
 
Search WWH ::




Custom Search