Lazy field initialization with lambdas

后端 未结 14 2314
日久生厌
日久生厌 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:10

    How about this. Some J8 functional switcheroos to avoid ifs on each access. Warning: not thread aware.

    import java.util.function.Supplier;
    
    public class Lazy {
        private T obj;
        private Supplier creator;
        private Supplier fieldAccessor = () -> obj;
        private Supplier initialGetter = () -> {
            obj = creator.get();
            creator = null;
            initialGetter = null;
            getter = fieldAccessor;
            return obj;
        };
        private Supplier getter = initialGetter;
    
        public Lazy(Supplier creator) {
            this.creator = creator;
        }
    
        public T get() {
            return getter.get();
        }
    
    }
    

提交回复
热议问题