@FunctionalInterface
Marks an interface with exactly one abstract method — it can be implemented with a lambda.
Available since: Java 8
Syntax
@Documented @Retention(RUNTIME) @Target(TYPE) public @interface FunctionalInterfaceExamples
A custom functional interface and lambdas for it:
@FunctionalInterface
interface Discount {
double apply(double price);
}
void main() {
Discount none = price -> price;
Discount tenPercent = price -> price * 0.9;
IO.println(none.apply(200));
IO.println(tenPercent.apply(200));
}Output:
200.0
180.0A second abstract method is a compile error:
@FunctionalInterface
interface Discount {
double apply(double price);
String name();
}
void main() {
}Output:
Main.java:1: error: Unexpected @FunctionalInterface annotationNotes
The annotation is optional: any interface with one abstract method can be implemented with a lambda. It only records the intent and prevents accidentally adding a second abstract method. default and static methods, as well as Object methods (equals, toString), do not count. Before writing your own interface, check the ready-made ones in java.util.function: Function, Predicate, Supplier, Consumer.
See also
- -> (lambda) — A lambda expression — a short function that can be passed around as a value.
- interface — Declares an interface — a set of methods that a class promises to implement.
- Function — A function that takes a value of type `T` and returns a value of type `R`.
- Predicate — A condition: a function that takes a value and returns a `boolean`.
In the tutorial
- Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.