Currently getting into Java 8 lambda expressions and method references.
I want to pass a method with no args and no return value as argument to another method. This is how I am doing it:
public void one() {
System.out.println("one()");
}
public void pass() {
run(this::one);
}
public void run(final Function function) {
function.call();
}
@FunctionalInterface
interface Function {
void call();
}
I know there is a set of predefined functional interfaces in java.util.function such as Function<T,R> but I didn't find one with no arguments and not producing a result.
Paul Croarkin
14.7k16 gold badges82 silver badges120 bronze badges
asked Aug 7, 2014 at 15:18
Torsten Römer
4,0324 gold badges45 silver badges57 bronze badges
2 Answers 2
It really does not matter; Runnable will do too.
Consumer<Void>,
Supplier<Void>,
Function<Void, Void>
answered Aug 8, 2014 at 8:39
Joop Eggen
110k8 gold badges89 silver badges142 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Stuart Marks
Runnable is best. With Supplier<Void> or Function<Void,Void> you may be forced to supply null as the return value (since the return type is Void not void), and for Consumer<Void> you may have to declare a dummy argument.Joop Eggen
@StuartMarks, that comment will certainly help others to pick by their sense of style. Weird that there is no java.util.Action/SideEffect or so. so.
Stuart Marks
The problem with these interfaces is that they have no semantics; they are entirely structural. The semantics come from how they're used. Since they can be used many different ways, naming them is really hard. It would make good sense for an interface that takes an event and returns void to be called
Action instead of Consumer<Event> but Action makes less sense in other contexts. Thus the names were mostly chosen to reflect structure, that is, arguments passes and values returned.Joop Eggen
@StuartMarks Agreed, as lambdas mostly are used anonymously, maybe even
_ (underscore) could be used as function name. In general Function is a good neutral catch-all, though Void misses void as return value, and () as parameter value.You can also pass lambda like this:
public void pass() {
run(()-> System.out.println("Hello world"));
}
public void run(Runnable function) {
function.run();
}
In this way, you are passing lambda directly as method.
Comments
Explore related questions
See similar questions with these tags.
lang-java
Supplier<Void>, Function<Void, Void>.