Search code examples
javalambdajava-8void

Java 8 lambda Void argument


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?


Solution

  • The syntax you're after is possible with a little helper function that converts a Runnable into Action<Void, Void> (you can place it in Action for example):

    public static Action<Void, Void> action(Runnable runnable) {
        return (v) -> {
            runnable.run();
            return null;
        };
    }
    
    // Somewhere else in your code
     Action<Void, Void> action = action(() -> System.out.println("foo"));