We will take a look at most common and most useful Kotlin standard delegates.
To do lazy initialization we will use lazy delegate. Let's take a look at example (Lazy.kt):
class UsesLazy {
val myLazyValue: String by lazy {
println("I am initializing this lazy value!")
"My lazy value!"
}
}
fun useLazy(){
val usesLazy: UsesLazy = UsesLazy()
val a: String = usesLazy.myLazyValue
val b: String = usesLazy.myLazyValue
val c: String = usesLazy.myLazyValue
}
Console output:
I am initializing this lazy value!
By default, the evaluation of lazy properties is synchronized! The value is computed only in one thread, and all threads will see the same value.
Next delegate we will demonstrate is observable. Let's take a look at example (Observable.kt):
class ObservableExample {
var toBeDelegated: String by Delegates.observable("Initial value!") {
property, oldValue, newValue ->
println("[ old: $oldValue ][ new: $newValue ]")
}
}
fun observeValueChanges(){
val observe = ObservableExample()
observe.toBeDelegated = "Some new value"
observe.toBeDelegated = "And some more..."
observe.toBeDelegated = "And more... ;)"
}
We will execute method observeValueChanges() to trigger observable delegate and get the following console output:
[ old: Initial value! ][ new: Some new value ]
[ old: Some new value ][ new: And some more... ]
[ old: And some more... ][ new: And more... ;) ]