val - this is a read only property. You need an operator getValue()
var - this is a read and write property. You need an operator getValue() and setValue()
syntax:
getValue(object, property)
1. object - it should be your class or a super class of your class. Your class here means the class that has the property to be delegated and not the representative class.
2. property - must be of type KProperty<*> or its super type.
setValue(object, property, value)
1. object - it should be your class or a super class of your class. Your class here means the class that has the property to be delegated and not the representative class.
2. property - must be of type KProperty<*> or its super type.
3. value - must be of the same type as of the property
==================
import kotlin.reflect.KProperty
fun main(){
val obj = YourClass()
println("message: ${obj.message}")
obj.message = "Hello Kotlin"
println("message now: ${obj.message}")
}
class YourClass{
var message: String by ClassRepresentative()
}
class ClassRepresentative {
private var string: String = "Hello World"
operator fun getValue(obj: YourClass, property: KProperty<*>): String{
return string
}
operator fun setValue(obj: YourClass, property: KProperty<*>, value: String){
string = value
}
}
==================
Result:
message: Hello World
message now: Hello Kotlin
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...
