Lazy field initialization with lambdas

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

    Here's a way that also works if you want to pass arguments (which you dont have when initializing the functional interface) to your expensiveInit method.

    public final class Cache {
        private Function, T> supplier;
    
        private Cache(){
            supplier = s -> {
                T value = s.get();
                supplier = n -> value;
                return value;
            };
        }   
        public static  Supplier of(Supplier creater){
            Cache c = new Cache<>();
            return () -> c.supplier.apply(creater);
        }
        public static  Function of(Function creater){
            Cache c = new Cache<>();
            return u -> c.supplier.apply(() -> creater.apply(u));
        }
        public static  BiFunction of(BiFunction creater){
            Cache c = new Cache<>();
            return (u, v) -> c.supplier.apply(() -> creater.apply(u, v));
        }
    }
    

    Usage is the same as Stuart Marks' answer:

    private final Function lazyBar = Cache.of(this::expensiveBarForFoo);
    

提交回复
热议问题