Data classes are not really created for this. Since their properties must be declared in the main constructor, you cannot add custom behavior to them.
However, if you need to, you can achieve this by duplicating properties, and then either using custom setters, or Delegates.observable.
, name age, , :
data class Person(private var _name: String, private var _age: Int) {
var name = _name
set(value) {
println("Name changed from $name to $value")
field = value
_name = value
}
var age = _age
set(value) {
println("Age changed from $age to $value")
field = value
_age = value
}
}
, Delegates.observable, , - , , :
data class Person(private var _name: String, private var _age: Int) {
var name: String by Delegates.observable(_name) { prop, old, new ->
println("Name changed from $old to $new")
_name = new
}
var age: Int by Delegates.observable(_age) { prop, old, new ->
println("Age changed from $old to $new")
_age = new
}
}
(toString ):
val sally = Person("Sally", 50)
println(sally)
sally.age = 51
println(sally)
println(sally.name)
println(sally.age)
, :
, , :
class Person(name: String, age: Int) {
var name: String by Delegates.observable(name) { _, old, new ->
println("Name changed from $old to $new")
}
var age: Int by Delegates.observable(age) { _, old, new ->
println("Age changed from $old to $new")
}
}
, , , , . , - ( val var). constructors, properties .