Better applicability to make a functional interface

6

From Java 8, in order for an interface to become functional, does it need to have just one method? But we have the @FuncionalInterface annotation, which explicitly defines that this interface is functional.

But what is the main difference in using this annotation or not, if with only one method it already becomes functional?

    @FunctionalInterface
public interface FuncionalInterface <T>{
    boolean valida(T t);
}

public interface FuncionalInterface <T>{
    boolean valida(T t);
}

When printing the result is the same either with the annotation or without, look at the main:

public static void main(String[] args) {
    FuncionalInterface<String> funcionalInterface = valor -> valor.matches("[0-9]{5}-[0-9]{3}");
    System.out.println(funcionalInterface.valida("45680-000"));

}
    
asked by anonymous 30.03.2016 / 06:42

2 answers

8

As described in the documentation , this annotation is primarily meant to declare its intention that it be used as a functional interface.

One of the aspects is to leave this intention explicit and documented in the code, which is good practice.

Documentation that is part of the code allows a number of features that do not necessarily affect system execution, but can serve as a hint for your IDE to properly complete the code, for the compiler to perform some additional operation or verification or even for the next programmer who will use their classes and will not read the system manual.

In this case, as also cited in the documentation, this annotation requires the compiler to issue errors in the following cases:

  • The type in question is not an interface
  • The interface does not meet the criteria of a functional interface

So the main difference is that if you add one more method to the two interfaces that you put in the question, one will compile and the other will not.

Consider the case of an interface that is used by another system and not just by its own code. Adding one more method can do no harm to your code, but it can break third-party code.

So, in a practical way, the least that the annotation does is to remind you every time you to the class that it is not a good idea to put another method there.

    
30.03.2016 / 11:35
5

You do not have to do anything special for an interface to be considered functional. The compiler already identifies this type of interface by its structure.

The @FunctionalInterface annotation serves as the fact that it is a functional interface, it is not for the simple coincidence of having a single method. To do this, we use the annotation @FuncionalInterface :

Mark your interface with the annotation and trigger any other method on it, you will soon see that the compiler has reported an error.

    
30.03.2016 / 15:20