7

I was wondering why on the Java8 API the Optional class have the method ifPresent(Consumer< T> consumer) and not the ifNotPresent(Runnable** consumer)?

What's the intent of the API? Isn't it to emulate the functional pattern matching?

** Java doesn't have a zero argument void functional interface...

5
  • 3
    oracle.com/technetwork/articles/java/… Commented Apr 2, 2015 at 23:15
  • 1
    It is because the computation should be side effect free, so if I need to execute something when the computation fail, in the case it doesn't fail I will do nothing with the result, but lose it...ok now it's clear, thank you! Commented Apr 2, 2015 at 23:25
  • 7
    .ifPresentOrElse is in the pipeline for jdk9: see mailing list discussion Commented Apr 2, 2015 at 23:44
  • 3
    Runnable is indeed the zero-arg void functional interface. And the second argument of the new JDK 9 Optional.ifPresentOrElse is Runnable. Commented Apr 3, 2015 at 2:06
  • I know about the Runnable but it was created for another scope, it's just a matter to make the intent of a function explicit :) cheers Commented Apr 3, 2015 at 23:00

1 Answer 1

10

As Misha said, this feature will come with jdk9 in the form of a ifPresentOrElse method.

/**
 * If a value is present, performs the given action with the value,
 * otherwise performs the given empty-based action.
 *
 * @param action the action to be performed, if a value is present
 * @param emptyAction the empty-based action to be performed, if no value is
 *        present
 * @throws NullPointerException if a value is present and the given action
 *         is {@code null}, or no value is present and the given empty-based
 *         action is {@code null}.
 * @since 9
 */
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
    if (value != null) {
        action.accept(value);
    } else {
        emptyAction.run();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.