https://kotlinlang.org logo
k

Konstantin Tskhovrebov

12/12/2019, 3:48 PM
Hello, is there a way in Kotlin to use property delegates for data classes in constructor? I want to create something like Swift's
Property Wrapper
https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID617
k

Kris Wong

12/12/2019, 3:51 PM
b

Big Chungus

12/12/2019, 3:56 PM
data class Entity: InterfaceOfSmth by ClassThatImplementsSomethingOfThatInterface()
k

Konstantin Tskhovrebov

12/12/2019, 3:58 PM
@Kris Wong no. I didn't find how change getter for data class property 😢
b

Big Chungus

12/12/2019, 4:00 PM
You can always add secondary constructor that delegates props from args
k

Konstantin Tskhovrebov

12/12/2019, 4:00 PM
Swift's
Property Wrapper
changes getter's logic inside binary representation (how i understood)
k

Kris Wong

12/12/2019, 4:01 PM
kotlin has the same concept. add a normal property to your data class and provide the getter and setter.
k

Konstantin Tskhovrebov

12/12/2019, 4:02 PM
@Big Chungus but than i will lost all data class features (like auto
toString()
method)
b

Big Chungus

12/12/2019, 4:02 PM
Nope
You'll just do the conversion of your constructor args at instantiation. Resulting class will still be the same
k

Konstantin Tskhovrebov

12/12/2019, 4:36 PM
No. For example: If i use property wrapper than system log prints property via custom getter. But data class doesn't use property delegate for generating toString() method.
b

Big Chungus

12/12/2019, 4:51 PM
Then as @Kris Wong mentiones override getters
This still won't break equals and toString
Remember that every val and var have getters setters behind them
k

Konstantin Tskhovrebov

12/12/2019, 9:12 PM
No,
toString()
method uses properties without getters but i want to change value before print it to log

https://www.youtube.com/watch?v=nIGlxcUES_Q

How I understand that Kotlin hasn't feature like
Property Wrapper
3 Views