0 votes
1 view
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

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"));

Related questions

0 votes
1 answer
asked Nov 19, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...