lazy properties - the value of the property is computed only on its first invocation.
observable properties - when the value of the property changes, its listener is notified.
Note: You can store properties in a map rather than a separate field for each property.
delegated properties - this a property that relies on a helper class getValue() and setValue() operator which requires not less than two parameters. You have to import this KProperty in your helper class. This KProperty is required.
import kotlin.reflect.KProperty
syntax:
class YourClass{
var name: Type by YourRepresentativeClass()
}
class YourRepresentativeClass{
operator fun getValue(object: Any?, description: KProperty<*>): String{
return "Object: $object Property: ${description.name}"
}
operator fun setValue(object: Any?, description: KProperty<*>, value: String){
println("Object: $object Property: ${description.name} value: $value")
}
}
during invocation... Just create an instance of your class. So, you can get and set the property of your class. It will automatically refer to the getValue() and setValue() operator.
fun main(){
val del = YourClass()
del.name = "Whatever value"
println(del.name)
}
The result would be:
Object: YourClass.... Property: name value: Whatever value
Object: YourClass.... Property: name
======================
import kotlin.reflect.KProperty
fun main(){
val del = JustForDelegation()
del.representative = "Slime"
println(del.representative)
}
class JustForDelegation{
var representative: String by YourHelper()
}
class YourHelper{
operator fun getValue(obj: Any?, desc: KProperty<*>):String{
return "Object: $obj Property: ${desc.name}"
}
operator fun setValue(obj: Any?, desc: KProperty<*>, value: String){
println("Object: $obj Property: ${desc.name} value: $value")
}
}
=======================
Result:
Object: JustForDelegation... Property: representative value: Slime
Object: JustForDelegation... Property: representative
YOU ARE READING
Kotlin Programming
RandomI have been trying to learn things online. I will put my notes in here. I put things in my own words and i do not copy their programs. I try to do things the right way so that i may learn. Below is the site where i study. Go check this out if you wa...
