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()}}
use this code
classUser{varfirstName:String?byTrimDelegate()varlastName:String?byTrimDelegate()// to print objectoverridefuntoString():String{return"$firstName $lastName"}}
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}}
funmain(args:Array<String>){valuser1=User()user1.firstName=" justin "user1.lastName=" Bieber "print(user1.firstName)// justinprint("\n$user1")//justin Bieber}
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse