Skip to content

Instantly share code, notes, and snippets.

@ViksaaSkool
Last active December 9, 2018 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ViksaaSkool/cd27c9eee12d90557a6a0327e08c982c to your computer and use it in GitHub Desktop.
Save ViksaaSkool/cd27c9eee12d90557a6a0327e08c982c to your computer and use it in GitHub Desktop.
DelegatedProperties
//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