Lazy field initialization with lambdas

后端 未结 14 2285
日久生厌
日久生厌 2020-11-29 23:39

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

14条回答
  •  一向
    一向 (楼主)
    2020-11-30 00:30

    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.

提交回复
热议问题