Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy evaluation of Optional

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).

like image 581
Giovanni Lovato Avatar asked Jun 01 '17 14:06

Giovanni Lovato


1 Answers

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.

like image 73
Ondra Žižka Avatar answered Oct 03 '22 23:10

Ondra Žižka