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?
That is not possible. A function that has a non-void return type (even if it's
Void
) has to return a value. However you could add static methods toAction
that allows you to "create" aAction
:That would allow you to write the following:
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 toThunk
in general CS terms).Use
Runnable
if it does neither and cannot throw.You can create a sub-interface for that special case:
It uses a default method to override the inherited parameterized method
Void execute(Void)
, delegating the call to the simpler methodvoid execute()
.The result is that it's much simpler to use:
Add a static method inside your functional interface
Output
The lambda:
actually represents an implementation for an interface like:
which is completely different than the one you've defined. That's why you get an error.
Since you can't extend your
@FunctionalInterface
, nor introduce a brand new one, then I think you don't have much options. You can use theOptional<T>
interfaces to denote that some of the values (return type or method parameter) is missing, though. However, this won't make the lambda body simpler.Just for reference which functional interface can be used for method reference in cases method throws and/or returns a value.