What is a functional interface in Java, and how does the compiler know a lambda can be assigned to it?
A functional interface is an interface with exactly one method that is not already implemented. That one method is called the abstract method, and it is the method that a lambda or a method reference stands in for.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
// The compiler knows that this is a functional interface.
Transformer<String, Integer> length = text -> text.length();
System.out.println("length : " + length.transform("hello"));
// The built in ones are functional interfaces as well.
Function<String, Integer> builtIn = String::length;
System.out.println("same answer : " + builtIn.apply("hello"));
}
}
@FunctionalInterface
public interface Transformer<A, B> {
B transform(A value);
}
So how does the compiler know? You tell it with the annotation @FunctionalInterface. The annotation is checked when the code compiles, so if you add a second abstract method to the interface by accident, the build fails with a message that says exactly that.
The annotation is not strictly needed for a lambda to work. The compiler can work out the target type from the place where the lambda is used. But the annotation is always worth adding, because it turns a mistake that would only show up later into a mistake that the compiler catches straight away, and it tells the reader that the interface is meant to be used this way.
The standard library has a whole set of these in the package java.util.function. The most useful ones are Function, which takes one value and gives one back, Consumer, which takes a value and gives nothing back, Supplier, which takes nothing and gives one back, and BiFunction, which takes two values and gives one back.
The next question in this topic looks at what you can add to an interface of your own.