DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Updated on • Originally published at sanjayprajapat.hashnode.dev

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()
        }

}
Enter fullscreen mode Exit fullscreen mode

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"  
        } 
}
Enter fullscreen mode Exit fullscreen mode

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
    }

}
Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {

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

}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)