Functional Interface Photo

Functional Interface

1. What is a Functional Interface

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 a 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 Java compiler.

Example 1. Use of @FunctionalInterface annotation

public interface SomeInterface {
    void doSomething();

2. Function Descriptor

Function descriptor term is used describe the signature of the Functional interface abstract method and lambda expression. 

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

() -> void

Let's write function descriptor for the next examples:

Example 2. Function Descriptor

public interface SomeInterface1 {
    int someMethod1(String param);

The function descriptor is:

String -> int

Example 3. Function Descriptor

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

public interface Consumer<T> {
    void accept(T t);

The Function descriptor of the consumer interface is:

T -> void

Functional Interfaces Photo

Read also: