Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Edited on • Originally published atsanjayprajapat.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 */classUser{varfirstName:String?=nullset(value){if(value!=null)field=value.trim()}varlastName:String?=nullset(value){if(value!=null)field=value.trim()}}
Enter fullscreen modeExit fullscreen mode

use this code

classUser{varfirstName:String?byTrimDelegate()varlastName:String?byTrimDelegate()// to print objectoverridefuntoString():String{return"$firstName $lastName"}}
Enter fullscreen modeExit fullscreen mode

create custom Delegate class and name itTrimDelegate

classTrimDelegate{privatevartrimmedString:String?=null// thisRef is calling objectoperatorfunsetValue(thisRef:Any,property:KProperty<*>,value:String?){// (thisRef as User).firstName // to access membervalue?.let{trimmedString=it.trim()}}operatorfungetValue(thisRef:Any,property:KProperty<*>):String?{returntrimmedString}}
Enter fullscreen modeExit fullscreen mode
funmain(args:Array<String>){valuser1=User()user1.firstName="  justin "user1.lastName=" Bieber    "print(user1.firstName)// justinprint("\n$user1")//justin Bieber}
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Android Developer
  • Location
    Jodhpur, Rajasthan
  • Work
    Android Developer at Sculptsoft
  • Joined

More fromSanjay Prajapat

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp