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.