Kotlin

observable — Listen for Property Changes

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`Delegates.observable(initial) { prop, old, new -> ... }` fires a callback every time the property changes. Useful for state-tracking, simple observability without a full reactive lib.
Kotlin
Raw
import kotlin.properties.Delegates

class User(name: String, age: Int) {
    var name: String by Delegates.observable(name) { _, old, new ->
        println("name changed: $old → $new")
    }

    var age: Int by Delegates.observable(age) { _, old, new ->
        println("age changed: $old → $new")
    }
}

fun main() {
    val u = User("Alice", 30)
    u.name = "Alyce"                                    // prints: name changed: Alice → Alyce
    u.age  = 31                                         // prints: age changed: 30 → 31

    // vetoable — same idea, but you can REJECT the change
    var port: Int by Delegates.vetoable(8080) { _, old, new ->
        new in 1..65535                                  // only allow valid ports
    }
    port = 9090
    port = -1                                            // rejected; port stays 9090
    println(port)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.