0Pricing
Kotlin Academy · Lesson

observable and vetoable Delegates

React to property changes with observable and conditionally reject with vetoable.

Property Delegates Refresher

Kotlin property delegates let a separate object handle getValue and setValue. Delegates.observable and Delegates.vetoable are built-in delegates from the standard library.

import kotlin.properties.Delegates
var name: String by Delegates.observable("initial") { prop, old, new ->
    println("${prop.name}: $old -> $new")
}
fun main() { name = "Alice"; name = "Bob" }

observable Syntax

observable takes an initial value and a callback invoked after each change with the property, old value, and new value.

import kotlin.properties.Delegates
var score: Int by Delegates.observable(0) { _, old, new ->
    println("Score changed from $old to $new")
}
fun main() {
    score = 10
    score = 25
    score = 0
}

All lessons in this course

  1. by lazy: Deferred Initialization Deep Dive
  2. observable and vetoable Delegates
  3. Writing a Custom ReadWriteProperty Delegate
  4. Delegates for Preferences, Map-Backed Properties & Logging
← Back to Kotlin Academy