Card 03/ 09

ConceptDifficulty: Intermediate1 min

What Makes an Interface Functional, and Why the Number Matters

A lambda supplies one method body. For that to be unambiguous, the interface it lands in has to be missing exactly one method — no more and no fewer.

An interface with exactly one abstract method is a functional interface, and a lambda may be used wherever one is expected.

java
@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.

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.