Is this a bug or function?
Below with NPE
Function<String, String> f = null; Optional.<String>empty().map(f).orElse(null);
But not
Function<String, String> f = null; Optional.<String>empty().map(value -> f.apply(value)).orElse(null);
IntelliJ, for example, will suggest replacing the second expression with the first as equivalent, which has made sense to me so far.
The reason for this behavior is the implementation of Optional#map() :
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) { // check happens before the branching Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Optional.ofNullable(mapper.apply(value)); } }
Instead, if map() was implemented using:
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) { if (!isPresent()) return empty(); else {
we get consistent behavior between two 2 fragments. Any reason map() not the second implementation?
source share