java-8functional-interface

Why to use @FunctionalInterface annotation in Java 8


If we have Interface with only one abstract method in it, it is by default Functional Interface. Can anyone please explain what additional advantage @FunctionalInterface annotation brings?

I know that if we add @FunctionalAnnotation, it will not allow someone to add another abstract method in the interface, as it will give a compilation error, but my point is even if you don't use @FucntionalInterface annotation, then also, if someone will add another abstract method, it will break all the existing lambda expressions in the code and compiler will complain.

For example:

If I have the following Interface:

public interface User {
    
    Integer fetchData(Integer userId);
}

with following implementation:

public class UserImpl implements User{

    @Override
    public Integer fetchData(Integer userId) {
        return 1;
    }
}

and following usage :

public class TestFunctionalInterface {
    
    public static void main(String[] args) {
        User user = a -> a*2;
        System.out.println("FetchedData:"+user.fetchData(2));
    }

}

And now, if I try to add another method in the interface like below:

public interface User {
    
    Integer fetchData(Integer userId);
    
    Integer fetchLoginDetails(Integer userId);

}

Compiler is complaining in below code:

public class TestFunctionalInterface {
    
    public static void main(String[] args) {
        User user = a -> a*2;
        System.out.println("FetchedData:"+user.fetchData(2));
    }

}

at line User user = a -> a*2;

With message "The target type of this expression must be a functional interface".


Solution

  • The main advantage to protect your interface by @FunctionalInterface is when you use lambda to instantiate them.

    Lambda declaration can only declare one block of code so if there is no protection on your interface and some will add an abstract method your lambda have no more sense ...

    that why its highly recommend to not implement with lambda some implicit functional interface.

    So if you want to implement this interface by lambda way I encourage you to add the annotation that s a security. if you don't want this kind of implementation or if your interface will change or have an night risk to change don t had it.