Java 8 introduced lambda expressions together with the package java.util.function. This Package consists basically of standard interfaces for
- Suppliers:
() → T - Consumers:
t -> void - Functions:
t -> r - Predicates:
t -> boolean - Operators:
t -> t - Other fixed type FunctionalInterfaces or variations that take or return more than one argument.
I was wondering why there's no standard interface for a classic callback: Zero arguments and no return value:
- Callback:
() -> void
Example implementation:
@FunctionalInterface
interface Callback {
void call();
default Callback andThen(Callback after) {
Objects.requireNonNull(after);
return () -> {
call();
after.call();
};
}
}
Example use case:
MyTask task = new MyTask();
AtomicInteger finishedTasks = new AtomicInteger();
task.finished(() -> System.out.println(finishedTasks + " tasks finished"));
task.finished(() -> schedule(task, 1, TimeUnit.HOURS));
schedule(task, 1, TimeUnit.HOURS));
The closest interface would be Runnable but that's a bit too much related to multithreading.
My questions:
- Do you know if Java provides this interface?
- Where do I find a list of classes that are annotated with
@FunctionalInterface?