Lazy field initialization with lambdas

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

    Within your actual lambda, you can simply update the fooField with a new lambda, such as:

    class A{
        private Supplier fooField = () -> {
           T val = expensiveInit();
           fooField = () -> val;
           return val;
        };
    
        public T getFoo(){
           return fooField.get();
        }
    }
    

    Again this solution is not thread-safe as is the .Net Lazy, and does not ensure that concurrent calls to the getFoo property return the same result.

提交回复
热议问题