Java 9: Executing fallbacks with Optional::or

Java 9 comes with an additional Optional.or method with the following functionality:

"If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function."

The method Optional::or is useful for the implementation of fallback logic. The example below return an Integer with the value 42:


import java.util.Optional;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;

public class OptionalTest {

    @Test
    public void or() {
        int message = this.answer().
                map(Integer::parseInt).
                or(this::defaultAnswer).
                get();
        assertThat(message, is(42));
    }

    public Optional<String> answer() {
        return Optional.ofNullable(null);
    }

    public Optional<Integer> defaultAnswer() {
        return Optional.of(42);
    }
}    

The method answer returns null, therefore the method map is not executed. The (fallback) or branch is executed instead and returns directly the 42 as integer.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License