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?
The syntax you're after is possible with a little helper function that converts a
Runnable
intoAction<Void, Void>
(you can place it inAction
for example):I don't think it is possible, because function definitions do not match in your example.
Your lambda expression is evaluated exactly as
whereas your declaration looks like
as an example, if you have following interface
the only kind of function (while instantiating) that will be compatibile looks like
and either lack of return statement or argument will give you a compiler error.
Therefore, if you declare a function which takes an argument and returns one, I think it is impossible to convert it to function which does neither of mentioned above.