Home > Software design >  Updata data in Kotlin data class
Updata data in Kotlin data class

Time:10-14

I have a data class in Kotlin where I have values depending on each other,

for example

data class test(
   var a: Int = 0,
   var b: Int = 10   a,
)

If the value for a is updated I want the value for b to automatically change.

How can I do this?

CodePudding user response:

You can create a property backed by another one like this:

data class test(
    var a: Int = 0,
) {
    var b: Int
        get() = a   10
        set(value) {
            a = value - 10
        }
}

Or even make it an extension over test class.

Just note b won't be settable with constructor. it won't be automatically included in equals(), hashCode() and other methods. It actually makes sense, because it is effectively just a duplicate of a.

CodePudding user response:

You need a custom setter/delegate for a, but it can't be added for primary constructor property, so you can't use data class here, only a simple one:

class Test(a: Int = 0, var b: Int = 10   a) {
    var a by Delegates.observable(a) { _, _, newValue -> this.b = 10   newValue }
}

Also, if you want to enforce this relation between a and b you need to disable direct change of b value (including setting in the constructor):

class Test(a: Int = 0) {
    var a by Delegates.observable(a) { _, _, newValue -> this.b = 10   newValue }
    var b = 10   a
        private set
}
  • Related