Delegated properties In Kotlin

Delegated properties In Kotlin

Delegate is just class ,that help us to seperate all logic of getter and setters so it can be reused . if want to use same code for more than one property ,then don't need to apply same code for every property ex:

/* dont need to write this code */
class User{
    var firstName:String? =null 
        set(value){
            if(value!= null )
                field = value.trim()
        }

    var lastName:String? = null 
        set(value){
            if(value!= null )
                field = value.trim()
        }

}

use this code

class User{
        var firstName:String? by TrimDelegate()       
        var lastName:String? by TrimDelegate() 

        // to print object 
        override fun toString():String{
            return "$firstName $lastName"  
        } 
}

create custom Delegate class and name it TrimDelegate

class TrimDelegate {
    private var trimmedString:String ? = null 

    // thisRef is calling object 
    operator fun setValue( thisRef:Any,property:KProperty<*>, value:String?){
        // (thisRef as User).firstName // to access member 
        value?.let { 
            trimmedString = it.trim()
         }   
    }
    operator fun getValue(thisRef:Any, property:KProperty<*>):String?{
        return trimmedString
    }

}
fun main(args: Array<String>) {

    val user1 = User()
    user1.firstName = "  justin "
    user1.lastName = " Bieber    "
    print(user1.firstName ) // justin 
    print("\n$user1")//justin Bieber

}