Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Optional why not an ifNotPresent method?

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...

like image 907
rascio Avatar asked Apr 02 '15 23:04

rascio


People also ask

Why Should Java 8's Optional not be used in arguments?

Accepting Optional as parameters causes unnecessary wrapping at caller level.

Why is null better than Optional?

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.

Why is Java Optional empty?

In Java, the Optional object is a container object that may or may not contain a value. We can replace the multiple null checks using the Optional object's isPresent method. The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn't have any value.


1 Answers

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();
    }
}
like image 74
Ortomala Lokni Avatar answered Sep 28 '22 17:09

Ortomala Lokni