Java 8 lambda Void argument

Wickoo picture Wickoo · Apr 29, 2015 · Viewed 173.3k times · Source

Let's say I have the following functional interface in Java 8:

interface Action<T, U> {
   U execute(T t);
}

And for some cases I need an action without arguments or return type. So I write something like this:

Action<Void, Void> a = () -> { System.out.println("Do nothing!"); };

However, it gives me compile error, I need to write it as

Action<Void, Void> a = (Void v) -> { System.out.println("Do nothing!"); return null;};

Which is ugly. Is there any way to get rid of the Void type parameter?

Answer

x1a0 picture x1a0 · Oct 20, 2016

Use Supplier if it takes nothing, but returns something.

Use Consumer if it takes something, but returns nothing.

Use Callable if it returns a result and might throw (most akin to Thunk in general CS terms).

Use Runnable if it does neither and cannot throw.