Add EventListener

Let’s say I’ve the below code:

data class Person(val name: String) {
    var age: Int = 0
}
fun main() {
    val person = Person("John")
    person.age = 10
}

I need to add a listener, that listen for age changes, and alert me if age is less than 18, something like:

fn Person.age.on_change(): String {
   If (age < 18)  "person = ${person.name} is jus ${person.age} years old"
}
var age: Int by Delegats.observable(0) { old, new -> TODO() }

also interesting is Delegates.vetoable (see here)


That all said, you should be careful about using data classes with properties that are not part of the constructor. Those properties are not part of any of the utility methods provided by data classes (equals, hashCode, copy, componentN and toString)

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • equals() / hashCode() pair;
  • toString() of the form "User(name=John, age=42)" ;
  • componentN() functions corresponding to the properties in their order of declaration;
  • copy() function (see below).

https://kotlinlang.org/docs/reference/data-classes.html

1 Like

You are probably looking for observable - Kotlin Programming Language

1 Like