Video in progress
What do you understand by a functional interface, and why is the @FunctionalInterface annotation needed?
A functional interface is an interface with one abstract method. A lambda can only be assigned to such an interface type. @FunctionalInterface is not mandatory, but if someone adds a second abstract method, the compiler reports an error.
📖 Answer
@FunctionalInterface
interface PriceRule {
long apply(long price); // the single abstract method
default PriceRule andThen(PriceRule next) { // a default method is allowed
return p -> next.apply(apply(p));
}
}
PriceRule discount = p -> p * 90 / 100;
PriceRule tax = p -> p + p * 12 / 100;
long finalPrice = discount.andThen(tax).apply(100_000);
One detail: default and static methods don't count. Methods from Object (equals, toString) don't count either, which is why Comparator is a functional interface even though it declares equals.
An interface is functional even without the annotation. But adding it is a signal to other developers ("this was written for lambdas, don't add methods") plus a compiler check. I put it on every such interface I write myself.
Sign up to mark studied questions and save your progress.