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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started