Here's what I've got so far:
Optional<Foo> firstChoice = firstChoice();
Optional<Foo> secondChoice = secondChoice();
return Optional.ofNullable(firstChoice.orElse(secondChoice.orElse(null)));
This strikes me as both hideous and wasteful. If firstChoice is present I am needlessly computing secondChoice.
There's also a more efficient version:
Optional<Foo> firstChoice = firstChoice();
if(firstChoice.isPresent()) {
return firstChoice;
} else {
return secondChoice();
}
Here I can't chain some mapping function to the end without either duplicating the mapper or declaring another local variable. All of this makes the code more complicated than the actual problem being solved.
I'd much rather be writing this:
return firstChoice().alternatively(secondChoice());
However Optional::alternatively obviously doesn't exist. Now what?
question from:
https://stackoverflow.com/questions/32776705/whats-the-most-elegant-way-to-combine-optionals 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…