Lazy field initialization with lambdas

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

    How about this? then you can do something like this by using LazyInitializer from Apache Commons: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/concurrent/LazyInitializer.html

    private static Lazy _lazyDouble = new Lazy<>(()->1.0);
    
    class Lazy extends LazyInitializer {
        private Supplier builder;
    
        public Lazy(Supplier builder) {
            if (builder == null) throw new IllegalArgumentException();
            this.builder = builder;
        }
        @Override
        protected T initialize() throws ConcurrentException {
            return builder.get();
        }
    }
    

提交回复
热议问题