Link together multiple variables

It’s more an architectural question and currently it solves by observables or setters or something else. But what is the current best way to provide consistency of 2 (or more) variables: if one changes value, the second should be changed too? E.g. how to make it more optimized or simple?

class Human {
    var house: House? = null
}

class city {
    val humans = listOf<Human>()
    val houses = listOf<House>()

    fun demolish(house: House) {
        humans.forEach { human ->
            if (human.house == house) human.house = null
            houses.remove(house)
        }
    }
}

There are several ways to do what you want. The simplest way is to provide open and close methods for a house and not to forget to use them (or use use).

Another way is to create bindings like it is done in JavaFX. It will require using observable delegate or something similar.

2 Likes