I was reading about java annotation and a new doubt appears.
In the documentation explain the FunctionalInterface Annotation Type:
An interface with one abstract method declaration is known as a functional interface.The compiler verifies all interfaces annotated with a @FunctionalInterface that the interfaces really contain one and only one abstract method. A compile-time error is generated if the interfaces annotated with this annotation are not functional interfaces. It is also a compile-time error to use this annotation on classes, annotation types, and enums. The FunctionalInterface annotation type is a marker interface.
I did some test and I did not need to mark my interface with this annotation type. Then, my question is: Why do I need this annotation if every interface with one method is always a functional interface?
// @FunctionalInterface
interface Wizard {
int spell(String power);
}
class TestLambda {
public static void main(String[] args) {
Wizard gandalf = str -> str.length();
int power = gandalf.spell(args[0]);
System.out.println("The spell length is: " + power+ " points");
}
}
You don't have to annotate a functional interface with @FunctionalInterface
but it documents your intention of creating one and will generate a compile error if the interface is not a functional interface (i.e. only has one non default and non static method).
It's a bit like @Override
: you don't have to use it but it will prevent you from using a signature that does not match the parent class when overriding a method.
See also: Why isn't @FunctionalInterface used on all the interfaces in the JDK that qualify?