What is a functional interface, and how do you use one without writing a class for it?
A functional interface is an interface with exactly one abstract method. You can use one without writing a class for it by giving it a lambda expression.
public class Main {
public static void main(String[] args) {
java.util.function.Function<String, Integer> len = s -> s.length();
java.util.function.Predicate<String> longWord = s -> s.length() > 2;
System.out.println(len.apply("hello")); // 5
System.out.println(longWord.test("hi")); // false
}
}
And the interface itself is this.
public interface LengthOf {
int length(String text);
}
And you use it with a lambda, which is the short way of writing a class that has one method.
LengthOf len = s -> s.length();
LengthOf len2 = text -> text.length();
LengthOf len3 = (String text) -> text.length();
And there is a whole family of them in the standard library, and they cover most of what you need.
the interface the shape what it does
------------------- -------------------- ----------------------------
Function T -> R turns one thing into another
Consumer T -> void takes a thing and uses it
Supplier () -> T makes a thing
Predicate T -> boolean asks a yes or no question
BiFunction (T, U) -> R turns two things into one
And there is one detail worth knowing about, and it is about the default and the static methods. Since Java 8 an interface can have default methods and static methods, and those do not count towards the one abstract method. So a functional interface can have several methods and still be a functional interface, as long as only one of them is abstract.
public interface Validator {
// The one abstract method.
boolean isValid(String value);
// A default method. It does not count.
default boolean isValidOrEmpty(String value) {
return value == null || value.isBlank() || isValid(value);
}
// A static method. It does not count.
static Validator alwaysValid() {
return value -> true;
}
}
And there is one more thing that is worth knowing about, and it is the annotation that the compiler checks it with.
@FunctionalInterface
public interface LengthOf {
int length(String text);
}
That annotation does not make the interface functional. It makes the compiler check that there is exactly one abstract method, and so if you add a second one by accident then you get a compile error instead of a confusing message later.
So the rule to remember is this. One abstract method, and a lambda expression is the short way to give it a body.
The last question in this topic is about when to write your own.