Вячеслав Чернышов :
I have this construction:
if (Objects.isNull(user.getMartialStatus())) {
user.setMartialStatus(MartialStatus.MARRIED);
}
I have many of them, & I want to optimize code using functional interface. Okay. I write something like this:
public static <T> void processIfNull(T o, Supplier<Void> s) {
if (Objects.isNull(o)) {
s.get();
}
}
Then, I wait that this code shall work:
processIfNull(user.getMartialStatus(), () -> user.setMartialStatus(MartialStatus.MARRIED));
But IDEA write:
void is not compatible with Void
Please, tell me, what to do.
TRiNE :
As the error explains Void
is a class which is not equivalent to void
. Supplier<Void>
expects to return Void
like Supplier<String>
will expect String
object to return.
So your functional interface should be like below.
It has a void apply()
which matches the signature of () -> ...
@FunctionalInterface
public interface ActionIfNotNull {
void apply();
}
However when you search for an inbuild functional interface, you can come up with Runnable
as Jon Skeet suggested.
Solution
public static <T> void processIfNull(T o, Runnable s) { // instead of you Runnable can use your own functional interface like ActionIfNotNull
if (Objects.isNull(o)) {
s.run();
}
}