Using @FunctionalInterface on Custom Interfaces
You'll learn how to apply @FunctionalInterface to your own interfaces to clearly signal lambda compatibility and gain compile-time safety.
Now that you understand what the @FunctionalInterface annotation does and how it validates the single abstract method rule, it's time to use it on your own custom interfaces. This is where you transition from consuming built-in functional interfaces to creating your own specialized ones for your domain.
Why Annotate Your Custom Interfaces
When you create an interface intended for lambda expressions, adding @FunctionalInterface serves two critical purposes:
- Documentation: It explicitly tells other developers (and your future self) that this interface is designed to work with lambdas
- Compile-time safety: The compiler will immediately flag an error if you accidentally add a second abstract method, breaking lambda compatibility
Think of it like putting a "Single Occupancy" sign on a hotel room—it clarifies the intent and prevents accidental violations.
How to Apply It
Simply place @FunctionalInterface above any interface that has exactly one abstract method:
@FunctionalInterface
public interface StringProcessor {
String process(String input);
}
Now you can use it with lambdas:
StringProcessor toUpper = s -> s.toUpperCase();
StringProcessor reverse = s -> new StringBuilder(s).reverse().toString();
If you later try to add another abstract method, you'll get a compile error immediately, preventing bugs before they happen.
Best Practice
Always use @FunctionalInterface on custom interfaces meant for lambdas. While technically optional (the interface would still work without it), the annotation makes your code more maintainable and prevents future mistakes.
Key Takeaway: Apply @FunctionalInterface to custom interfaces with one abstract method to document lambda intent and catch accidental violations at compile time—it's both a safety net and clear communication.