0

I' m trying to understand @Functional interface from JDK and can't catch why did they create this annotation without a body?

I don't understand what is difference between using @FunctionalInterface in class description and not using? what does this annotation without params provide?

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Elenaxxx1
  • 19
  • 3
  • All functional interfaces are recommended to have an informative @FunctionalInterface annotation. This not only clearly communicates the purpose of this interface, but also allows a compiler to generate an error if the annotated interface does not satisfy the conditions. See https://www.baeldung.com/java-8-functional-interfaces – fantaghirocco Jun 11 '19 at 10:07
  • 3
    `@FunctionalInterface` annotation is used to ensure an interface can’t have more than one abstract method. The use of this annotation is optional. – Sudhir Ojha Jun 11 '19 at 10:08
  • It is purely a _marker_ interface, to signal that some annotated interface is intended to be used/usable as lambda, that it contains just _one_ function. Containing one function would mean calling `getDeclaredMethods` for counting, which is an unnecessary overhead. – Joop Eggen Jun 11 '19 at 10:09

1 Answers1

3

If you add it, someone won't be able to add more methods without breaking your functional interface and will get a compile time error:

Invalid '@FunctionalInterface' annotation; MyInterface is not a functional interface

If a type is annotated with this annotation type, compilers are required to generate an error message unless:

  • The type is an interface type and not an annotation type, enum, or class.
  • The annotated type satisfies the requirements of a functional interface.
Ori Marko
  • 56,308
  • 23
  • 131
  • 233