Last active
December 9, 2018 21:04
DelegatedProperties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//we have class called Delegate that defines how to get and set values | |
class Delegate { | |
operator fun getValue(thisRef: Any?, property: KProperty<*>): String { | |
return "$thisRef, thank you for delegating '${property.name}' to me!" | |
} | |
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { | |
println("$value has been assigned to '${property.name}' in $thisRef.") | |
} | |
} | |
//In order to implement the delegate you need to add it after "by" | |
class Example { | |
var p: String by Delegate() | |
} | |
//this means get and set are defined as in Delegate class, other classes can reuse this assignment definition, a.k.a Deletage | |
//Standard delegates: | |
/* Lazy */ | |
//function that takes a lambda and returns an instance of Lazy<T> which can serve as | |
//a delegate for implementing a lazy property: the first call to get() executes the | |
//lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result. | |
//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. | |
val lazyValue: String by lazy { | |
println("computed!") | |
"Hello" | |
} | |
fun main() { | |
println(lazyValue) | |
println(lazyValue) | |
} | |
/* Observable */ | |
//Delegates.observable() takes two arguments: the initial value and a handler for modifications. | |
//The handler gets called every time we assign to the property (after the assignment has been performed). | |
//It has three parameters: | |
//property being assigned to | |
//old value | |
//new value | |
class User { | |
var name: String by Delegates.observable("<no name>") { | |
prop, old, new -> | |
println("$old -> $new") | |
} | |
} | |
fun main() { | |
val user = User() | |
user.name = "first" | |
user.name = "second" | |
} | |
/* Lateinit */ | |
//identifies that the property should have a non-nullable value, but its assignment will be delayed. If the value is requested | |
//before it is assigned, it will throw an exception that clearly identifies the property being accessed. | |
class App : Application() { | |
companion object { | |
lateinit var instance: App | |
} | |
override fun onCreate() { | |
super.onCreate() instance = this | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment