Functional Interface Photo

Functional Interface

1. What is a Functional Interface

A functional interface is an interface with a single abstract method, called the functional method.

  • A functional interface can have any number of default methods.
  • A functional interface can declare an abstract method with the signature of one of the methods of java.lang.Object.

The most important usage of Functional interface is the possibility to pass its abstract method as lambda expressions.

The Java API has many one-method interfaces such as Runnable, Callable, Comparator, ActionListener, and others, which became functional interfaces in Java SE 8.

Java SE 8 has introduced a new @FunctionalInterface annotation to mark an interface, which is optional and works as a "hint" for the Java compiler.

Example 1. Use of @FunctionalInterface annotation

@FunctionalInterface
public interface SomeInterface {
    void doSomething();
}

2. Function Descriptor

The function descriptor term is used to describe the signature of the Functional Interface abstract method and lambda expression. 

Let's write a function descriptor for Example 1. Functional Interface SomeInterface has a method doSomething(), which doesn't receive parameters and returns a void value. Its function descriptor will look like:

() -> void

Let's write function descriptor for the next examples:

Example 2. Function Descriptor

@FunctionalInterface
public interface SomeInterface1 {
    int someMethod1(String param);
}

The function descriptor is:

String -> int

Example 3. Function Descriptor

@FunctionalInterface
public interface SomeInterface2 {
    void someMethod2(int a1, int a2);
}

The function descriptor will be:

(int, int) -> void

Example 4. Function Descriptor of the Consumer interface

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    ...
}

The Function descriptor of the consumer interface is:

T -> void
Read also:
Trustpilot
Trustpilot
Comments