0
0
Kotlinprogramming~5 mins

Observable property delegation in Kotlin

Choose your learning style9 modes available
Introduction

Observable property delegation lets you watch a variable for changes and react when it changes.

You want to update the user interface when a value changes.
You need to log or track changes to a variable.
You want to validate or react to new values automatically.
You want to trigger other actions when a property updates.
Syntax
Kotlin
var propertyName: Type by Delegates.observable(initialValue) { property, oldValue, newValue ->
    // code to run when property changes
}

The lambda receives the property, old value, and new value.

You must import kotlin.properties.Delegates to use observable.

Examples
This example prints a message whenever name changes.
Kotlin
import kotlin.properties.Delegates

var name: String by Delegates.observable("") { prop, old, new ->
    println("Name changed from '$old' to '$new'")
}
This example checks if the new age is negative and prints a message accordingly.
Kotlin
import kotlin.properties.Delegates

var age: Int by Delegates.observable(0) { _, old, new ->
    if (new < 0) println("Age can't be negative")
    else println("Age updated from $old to $new")
}
Sample Program

This program creates a Person with an observable name. When the name changes, it prints the old and new values.

Kotlin
import kotlin.properties.Delegates

class Person {
    var name: String by Delegates.observable("Unknown") { prop, old, new ->
        println("Property '${prop.name}' changed from '$old' to '$new'")
    }
}

fun main() {
    val person = Person()
    person.name = "Alice"
    person.name = "Bob"
}
OutputSuccess
Important Notes

Observable properties help keep your code clean by separating change handling from business logic.

Be careful to avoid infinite loops if you change the property inside the observer.

Summary

Observable delegation watches a property and runs code when it changes.

Use it to react to changes like updating UI or logging.

The observer lambda gets the property, old value, and new value.