var foo : Int by Delegates.observable("1") { property, oldValue, newValue ->
println("${property.name} was changed from $oldValue to $newValue")
}
foo = 2
The example prints foo was changed from 1 to 2
class MyDelegate {
operator fun getValue(owner: Any?, property: KProperty<*>): String {
return "Delegated value"
}
}
val foo : String by MyDelegate()
println(foo)
The example prints Delegated value
Consider Kotlin's Null Type system and WeakReference<T>.
So let's say we have to save some sort of reference and we wanted to avoid memory leaks, here is where WeakReference comes in.
take for example this:
class MyMemoryExpensiveClass {
companion object {
var reference: WeakR...