androidengineers.Book a session

Advanced Language Features

Delegated Properties & patterns (lazy, observable, vetoable)

article15 minHard

Delegate repeated property behavior

Property delegates encapsulate access behavior. lazy computes a value on first access. observable reacts after assignment, while vetoable can reject a proposed change before it becomes the stored value.

import kotlin.properties.Delegates

class Plan {
    val heading: String by lazy { "Study plan" }
    var minutes: Int by Delegates.vetoable(25) { _, _, proposed -> proposed > 0 }
}

fun main() {
    val plan = Plan()
    plan.minutes = -5
    check(plan.minutes == 25)
}

A silently vetoed assignment may be poor UX when a user expects an error message; use an explicit validating operation when failure must be reported. JVM lazy has selectable thread-safety modes, but safe lazy initialization does not make the initialized object's mutable internals thread-safe.

Exercise

Add an observable property recording old/new values into a test list. Confirm initialization and later assignment behavior separately. Access a lazy value twice and count initializer calls.

Check: do not assume delegates run at the same time or serve the same failure-reporting purpose.

Reference: Delegated properties

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Delegated Properties & patterns (lazy, observable, vetoable) | Kotlin Core Programming | Android Engineers