getValue is an operator function that supplies the value of a delegated property. When code reads `foo.p`, Kotlin forwards the access to the delegate’s getValue function, passing the receiving object and a KProperty reference. section 9.5.1
Implementing an observable delegate
import kotlin.reflect.KProperty class ObservableProperty(var value: Int, val observable: Observable) { operator fun getValue(thisRef: Any?, prop: KProperty<*>): Int = value operator fun setValue(thisRef: Any?, prop: KProperty<*>, newValue: Int) { val oldValue = value value = 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) } getValue returns the stored value; setValue handles updates. The property reference exposes the delegated property’s name, removing duplicated name strings from the delegate’s constructor. section 9.5.3
Delegated-property access follows a compact convention:
- Declare `var p: Type by Delegate()`; Kotlin stores the delegate in a hidden helper property. section 9.5.1
- Read `p` to invoke `delegate.getValue(thisRef, prop)`; assign to `p` to invoke setValue as well. section 9.5.1
- Use `prop.name` when delegate behavior needs the declared property’s name. section 9.5.3
Listing 9.26 Using a delegated property that stores its value in a map
class Person {
private val _attributes = mutableMapOf<String, String>()
fun setAttribute(attrName: String, value: String) {
_attributes[attrName] = value
}
var name: String by _attributes #1
}
A delegated property can store its value in a map; the property name becomes the map key through the standard Map getValue extension. section 9.5.5
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
}
A database-oriented delegate can implement getValue to retrieve a column and setValue to update it, allowing ordinary property syntax to represent persistence. section 9.5.6
