setValue is the operator function that receives writes to a delegated var. Its receiver identifies the object, its KProperty reference identifies the property, and newValue carries the assigned value. section 9.5.3 section 9.5.1
An observable delegate
class ObservableProperty(var propValue: Int, val observable: Observable) { operator fun getValue(thisRef: Any?, prop: KProperty<*>): Int = propValue operator fun setValue(thisRef: Any?, prop: KProperty<*>, newValue: Int) { val oldValue = propValue propValue = newValue observable.notifyObservers(prop.name, oldValue, newValue) } } class Person(val name: String, age: Int, salary: Int) : Observable() { var age by ObservableProperty(age, this) var salary by ObservableProperty(salary, this) }
When age changes, Kotlin forwards the assignment to the delegate’s setValue. The function can retain the old value, store the new one, and use prop.name to report which property changed. section 9.5.3
The same convention supports other storage strategies:
- A MutableMap supplies setValue automatically, using the delegated property’s name as its key. section 9.5.5
- A database framework can implement setValue on Column to update the corresponding database field when a property changes. section 9.5.6
operator fun <T> Column<T>.getValue(o: Entity, desc: KProperty<*>): T
{
// retrieve the value from the database
}
operator fun <T> Column<T>.setValue(o: Entity, desc: KProperty<*>, value: T)
{
// update the value in the database
}
Inspect the generic Column setValue signature used to connect delegated assignments with database updates. section 9.5.6
