Card 03/ 09
Functional Interfaces: Exactly One Abstract Method
Why a lambda needs the interface to be missing exactly one method body, no more and no fewer.
A functional interface is an interface with exactly one abstract method, that is, one method declared without a body. A lambda, a short function written inline such as i -> true, may be used wherever one is expected, because the lambda supplies that one missing body and there is no doubt which method it is.
An interface for a rule that decides whether an invoice is allowed:
@FunctionalInterface
interface Rule {
boolean permits(Invoice invoice);
default Rule negate() { return i -> !permits(i); }
static Rule always() { return i -> true; }
}The default and static methods do not count, because both already have bodies. Only line 3 is missing one, so a lambda supplied here is unambiguously permits.
@FunctionalInterface changes nothing at runtime and is worth writing anyway. It makes the compiler check the count, so adding a second abstract method fails the build here rather than failing at every call site that passed a lambda.
The rule is also why interfaces older than lambdas, such as Runnable and Comparator, accept them without any change: they already had one abstract method.
So "functional interface" is not a category of special interfaces. It is a count, and any interface that happens to satisfy it can take a lambda, including ones written before lambdas existed.
← → move through sections and cards