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.

Paul Croarkin
  • 14,496
  • 14
  • 79
  • 118
Torsten Römer
  • 3,834
  • 4
  • 40
  • 53

2 Answers2

66

It really does not matter; Runnable will do too.

Consumer<Void>,
Supplier<Void>,
Function<Void, Void>
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 14
    `Runnable` is best. With `Supplier` or `Function` you may be forced to supply `null` as the return value (since the return type is `Void` not `void`), and for `Consumer` you may have to declare a dummy argument. – Stuart Marks Aug 08 '14 at 19:14
  • 1
    @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. – Joop Eggen Aug 11 '14 at 08:09
  • 6
    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` but `Action` makes less sense in other contexts. Thus the names were mostly chosen to reflect structure, that is, arguments passes and values returned. – Stuart Marks Aug 11 '14 at 13:06
  • @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. – Joop Eggen Aug 11 '14 at 14:13
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.

obey
  • 796
  • 7
  • 16