propertieskotlindidset

Is there a didSet/willSet analog in Kotlin?


I love this Swift syntax; it's very helpful for many things:

var foo: Bar = Bar() {
    willSet {
        baz.prepareToDoTheThing()
    }
    didSet {
        baz.doTheThing()
    }
}

and I'd love to do this in Kotlin. However, I can't find the proper syntax!

Is there anything in Kotlin like this?

I expected the syntax to look like this, but I can't find anything of the sort:

var foo: Bar = Bar()
    willSet() {
        baz.prepareToDoTheThing()
    }
    didSet() {
        baz.doTheThing()
    }

Solution

  • Although Kotlin doesn't provide a built-in Swift-style solution for property changes observation, you can still do it in several ways depending on what your goal is.

    In any case, it's up to you to make sure that the code observing the changes doesn't set the property again as it will likely fall into infinite recursion, or else you might check it in the observing code whether the setter is called recursively.