Declare final variable, but set later

后端 未结 7 1572
梦毁少年i
梦毁少年i 2020-12-09 01:49

I know this is fairly simple topic, but I really want to wrap my head around it.

This is what I\'m trying to do, but it doesn\'t like the final modifier. Is there an

7条回答
  •  无人及你
    2020-12-09 02:02

    You can't. But you can guarantee no external object changes it if it's private and you don't have a setter for it.


    Alternatively, you can wrap the long value in another class - LazyImmutableLong. But this is a more verbose approach, and you probably don't need it (note: the class below is not thread-safe)

    class LazyImmutableLong {
    
        private Long value;
    
        public void setValue(long value) {
             if (this.value != null) {
                 return; // the value has already been set
             }
             this.value = value;
        }
        public long getValue() {return value;}
    }
    

    And in your activity

    private LazyImmutableLong id = new LazyImmutableLong();
    
    public void onCreate(..) {
        id.setValue(..);
    }
    

提交回复
热议问题