Java › Annotations
What is the purpose of the @FunctionalInterface annotation, and is it required for an interface to actually be treated as a functional interface?
IntermediateAnswer
@FunctionalInterface is a marker/documentation annotation that instructs the compiler to verify the annotated interface has exactly one abstract method (making it eligible for lambda expression assignment) -- it's not strictly required for an interface with a single abstract method to work as a functional interface (the compiler infers this structurally regardless), but omitting it removes the safety net where the compiler would otherwise immediately flag an accidental second abstract method being added later, which would silently break lambda compatibility.
@FunctionalInterface
public interface Calculator {
int calculate(int a, int b);
// Adding a second abstract method here would now cause a COMPILE ERROR, not a runtime surprise
}
Calculator add = (a, b) -> a + b;Real-world example A shared library interface is marked @FunctionalInterface specifically so that if a future contributor accidentally adds a second abstract method (breaking every lambda-based usage across dozens of consumers), the compiler catches this immediately at the library's own build time rather than the error surfacing confusingly at each consumer's build.