observable and vetoable

React to Changes

Delegates.observable(initial) { prop, old, new -> } calls the lambda after every change. Delegates.vetoable calls it before and can reject the change by returning false.

Example

import kotlin.properties.Delegates

class Profile {
    var name: String by Delegates.observable("Guest") { prop, old, new ->
        println("${prop.name} changed: $old -> $new")
    }

    var age: Int by Delegates.vetoable(18) { _, _, new ->
        val ok = new in 13..120
        if (!ok) println("age $new rejected")
        ok
    }
}

fun main() {
    val p = Profile()
    p.name = "Ankit"
    p.name = "Ankit Sharma"
    p.age = 25
    p.age = 7
    println("Final: ${p.name}, ${p.age}")
}

Output

name changed: Guest -> Ankit
name changed: Ankit -> Ankit Sharma
age 7 rejected
Final: Ankit Sharma, 25

notNull

Delegates.notNull<Int>() is like lateinit but also works with primitive types such as Int. Reading it before assignment throws IllegalStateException.

var userId: Int by Delegates.notNull()
// userId = 42 later, e.g. after login