How to use functional interface returning void?

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.

Upvotes: 7

Views: 2420

Answers (2)

Jan Held
Jan Held

Reputation: 654

As of Java 9 Optional has the ifPresentOrElse method, which could be used for this.

Optional
    .ofNullable(user.getMartialStatus())
    .ifPresentOrElse(o -> {}, () -> user.setMartialStatus(MartialStatus.MARRIED););

You could also replace the o -> {} by some NOOP Consumer if you like, like this:

private static final Consumer<Object> NOOP = o -> {};

...

Optional
    .ofNullable(user.getMartialStatus())
    .ifPresentOrElse(NOOP, () -> user.setMartialStatus(MartialStatus.MARRIED););

Anyway, I think the solution Trine came up with, is preferable, because it makes it much clearer, what's going on.

Upvotes: 0

Lahiru Jayakody
Lahiru Jayakody

Reputation: 5400

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();
    }
}

Upvotes: 3

Related Questions