Functional interfaces are ‘single-purpose’ interfaces designed to force the implementation of a single, abstract method.
They are very useful and synergise well with lambda expressions.
The syntax for functional interfaces is the Java Annotation @FunctionalInterface
:
@FunctionalInterface
interface Attackable {
void Attack();
}
Can only contain ONE method
Functional interfaces can only contain a single, non-static method. Any more will raise a compiler error:
multiple non-overriding abstract methods found in interface
Examples
Predicate<T>
The Predicate
functional interface is a generic interface that forces the implementation of a boolean test
method:
import java.util.function.Predicate;
public interface Predicate<T> {
boolean test(T t);
}
The aim of this interface is to make any implementations act as a ‘filter’. The term predicate means an operation which always returns a boolean value.
UnaryOperator<T>
The UnaryOperator
generic interface forces the implementation of an apply
method:
import java.util.function.UnaryOperator;
public interface UnaryOperator<T> {
T apply(T t);
}
This interface allows the implementation of *unaries, which are functions that take in an argument and return a value of the same type
For example, this can be used to implement logic gates, like NOT.