Java: Functional Interfaces

Functional interfaces are interfaces with a single method. This is a functional interface:

interface MyInterface {
    void method();
}

With lambdas

The above interface can be used as follows:

MyInterface o = () -> System.out.println("Hello World");
o.method();

Or, if a someMethod accepts a MyInterface as argument, you can provide a lambda directly:

someMethod(() -> System.out.println("Hello World"));

With method references

Similarly, you can use method references. Given this class

class Example {
    static void sayHello() {
        System.out.println("Hello World");
    }
}

You can do

MyInterface o = Example::sayHello;

or

someMethod(Example::sayHello);

For more examples, including use of instance methods and constructor references, see the Lambda Cheat Sheet.

Standard Functional Interfaces

A complete list of the functional interfaces provided by the Java API can be found here: Lambda Cheat Sheet.

Default Methods

Apart from a single abstract method, a functional interface can have additional default methods. This for example, is still a functional interface:

interface MyInterface {
    void method();

    default void methodX2() {
        method();
        method();
    }
}

@FunctionalInterface annotation

If you want to make sure you're not accidentally turning a functional interface into a non-functional interface, you can make your intention explicit by adding @FunctionalInterface. If you mess up, like below…

@FunctionalInterface
interface MyInterface {
    void method1();
    void method2(); // Can't have more than one abstract method!
}

…the compiler will give the following error:

MyInterface.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  MyInterface is not a functional interface
1 error

Further Reading

Comments

Be the first to comment!