I would like to implement lazy field initialization (or deferred initialization) without an if statement and taking advantage of lambdas. So, I would like to have the same b
Taking Miguel Gamboa’s solution and trying to minimize the per-field code without sacrificing its elegance, I came to the following solution:
interface Lazy extends Supplier {
Supplier init();
public default T get() { return init().get(); }
}
static Supplier lazily(Lazy lazy) { return lazy; }
static Supplier value(T value) { return ()->value; }
Supplier fieldBaz = lazily(() -> fieldBaz=value(expensiveInitBaz()));
Supplier fieldGoo = lazily(() -> fieldGoo=value(expensiveInitGoo()));
Supplier fieldEep = lazily(() -> fieldEep=value(expensiveInitEep()));
The per-field code only slightly bigger than in Stuart Marks’s solution but it retains the nice property of the original solution that after the first query, there will be only a lightweight Supplier which unconditionally returns the already computed value.