Property Delegate Requirements

5 0 0
                                        

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

Kotlin ProgrammingWhere stories live. Discover now