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.