Aside from user-defined delegates, the Kotlin library also provides some useful built-in delegates that can be used in our applications. One of these delegates is the observable delegate, which triggers when a value is assigned to the property.
The observable takes the following parameters:
- The first parameter is the initial value of the property
- The second parameter is a lambda expression that takes the property type, the old value, the new value, and the body of the lambda expression
The following example shows the observable delegate with the age and name properties of the Person class. This delegate observes the properties and is triggered every time the value of the property changes:
class Person {
var age : Int by Delegates.observable(0) { property, oldValue, newValue ->
println("oldValue $oldValue newValue $newValue")
...