Course contentsShow
← Java
Lesson 2421 of 2,87046. AnnotationsFree lesson

Best Practices: When to Use @FunctionalInterface

Learn recommended guidelines for applying @FunctionalInterface to maximize code maintainability and API clarity.

Best Practices: When to Use @FunctionalInterface

You'll learn when and why to apply @FunctionalInterface to write cleaner, safer functional code.

The Core Principle

Think of @FunctionalInterface as a safety label on a contract: it doesn't change what the interface does, but it signals intent and adds compiler protection. The key question isn't "Can I use it?" but "Should I use it?" — and the answer depends on whether you're designing an interface specifically for lambda expressions or method references.

When to Apply @FunctionalInterface

Always use it for explicitly functional APIs: If you're designing an interface that clients will implement with lambdas, add the annotation. This makes your intent crystal clear — you're promising this interface will remain lambda-compatible.

@FunctionalInterface
public interface DataProcessor {
    void process(String data);
}

Use it for public APIs and libraries: When others depend on your code, the annotation acts as a contract. It prevents you from accidentally adding a second abstract method in future versions, which would break all existing lambda implementations.

Skip it for internal utilities: If an interface is private or package-private and only used within your codebase, the annotation adds less value. You already have full control over changes.

Omit it for non-functional interfaces: If an interface isn't meant for lambda usage — even if it happens to have one abstract method — don't mislead readers with the annotation. The annotation communicates design intent, not just structure.

The Clarity Test

Ask yourself: "Will developers implement this with lambdas?" If yes, use @FunctionalInterface. It's documentation that the compiler enforces, making your API both self-explanatory and break-proof.

Key Takeaway: Use @FunctionalInterface on interfaces explicitly designed for lambda expressions, especially in public APIs, to signal intent and prevent accidental interface evolution that breaks lambda compatibility.