Kotlin: Delegates Cheat Sheet

Lazy – calculates value beforefirst usage

val i by lazy { print("init "); 10 }
print(i) // Prints: init 10
print(i) // Prints: 10

notNull – returns last set value, or throws an error if no value has been set

observable/vetoable – calls function every time value changes. In vetoable function also decides if the new value should be set.

var name by observable("Unset") { p, old, new ->
     println("${p.name} changed $old -> $new")
name = "Marcin"
// Prints: name changed Unset -> Marcin

Map/MutableMap – finds value on map by property name

val map = mapOf("a" to 10)
val a by map
print(a) // Prints: 10

Leave a Reply

Your email address will not be published. Required fields are marked *