DEV Community

Sanjay Prajapat
Sanjay Prajapat

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

1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay