Is it possibile to have an java.util.Optional
which is evaluated only if needed?
I need to pass an Optional
to a method (of an API that I cannot change), and this method may or may not make use the value of that Optional
. Since the value is computed by a heavy operation, I'd like to compute that value only when (and if) it is needed, e.g. calling get()
, orElseGet()
, ifPresent()
, etc.
Something like Optional.ofLazy(Supplier<T> computeValue)
.
What you want is a Supplier
which returns an Optional
. Supplier
makes the lazy part.
Conceptual code:
Foo heavyComputation() { ... }
void main() {
Supplier<Optional<Foo>> sup = () -> heavyComputation();
doSomethingWhichMayNeedHeavyResult(sup);
}
void doSomethingWhichMayNeedHeavyResult(Supplier<Optional<Foo>> sup) {
if (electricityIsTooCheap) {
Foo foo = sup.get().get().orElse(null); // This will lazy load.
}
}
For brevity, I would also like to have something which combines both into one, but that will come later I guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With