74

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.

2
  • 6
    It really does not matter; Runnable will do too. Supplier<Void>, Function<Void, Void>. Commented Aug 7, 2014 at 15:30
  • Oh yes, the good old Runnable... I knew I missed something obvious! You should make this an answer since you have answered my question :-) Commented Aug 7, 2014 at 15:53

2 Answers 2

66

It really does not matter; Runnable will do too.

Consumer<Void>,
Supplier<Void>,
Function<Void, Void>
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@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.
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.
@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.
46

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.