I'm wondering if someone can clarify my understand...
# getting-started
a
I'm wondering if someone can clarify my understanding of backing fields. I have this property defined in an `object`:
Copy code
val wordle = Wordle()
        get() {
            if (this.lastWordListRefresh + 1.hours < Clock.System.now()) {
                return Wordle().also {
                    <http://this.log.info|this.log.info>("Refreshing Wordle state")
                    this.lastWordListRefresh = Clock.System.now()
                }
            }
            return field
        }
My understanding was that returning a different value from
get
would set the backing field. But it seems that, if
lastWordListRefresh
has "expired", it returns a new object once, and then continues using the old backing object for subsequent calls. Is there a way to make it so that the value returned from
get
sets the backing field? I essentially want a property that expires, and then lazily refreshes itself.
d
The backing field is never automatically updated
You just need to update the backing field:
Copy code
val wordle = Wordle()
        get() {
            if (this.lastWordListRefresh + 1.hours < Clock.System.now()) {
                field = Wordle().also {
                    <http://this.log.info|this.log.info>("Refreshing Wordle state")
                    this.lastWordListRefresh = Clock.System.now()
                }
            }
            return field
        }
a
It seems that I have to change the property to a
var
in order to do that. If I don't define the setter, does that mean it can't be updated externally?
d
The setter would be public
But you can make it private:
Copy code
var wordle = Wordle()
        get() {
            if (this.lastWordListRefresh + 1.hours < Clock.System.now()) {
                field = Wordle().also {
                    <http://this.log.info|this.log.info>("Refreshing Wordle state")
                    this.lastWordListRefresh = Clock.System.now()
                }
            }
            return field
        }
        private set
👍 1
a
Thanks!
d
NP and good luck!