https://kotlinlang.org logo
Title
s

shirbal

06/26/2017, 6:50 PM
How do I write custom setters for a class variables where the class is data class ?
r

Ruckus

06/26/2017, 6:55 PM
shirbal: That's not what data classes are for. Data classes are simple containers for encapsulating data, not functionality.
s

shirbal

06/26/2017, 6:57 PM
it is probably worth mentioning that I am just checking the language abilities, not really want to do it. Want to make sure that a developer will not be able to do it. I am working on pushing the language to our stack and pointing some stuff, thanks
r

Ruckus

06/26/2017, 7:01 PM
I don't believe there is a way to declare custom getters or setters for properties defined in the primary constructor.
s

shirbal

06/26/2017, 7:38 PM
there are some hacks which you can do, for example make it private and define a public wrapper on top of it, similar to C# convention with properties
r

Ruckus

06/26/2017, 10:12 PM
You could, but then the generated functions would use the private property, and you may not represent the returns in the wrapped custom getters, which could be a serious issue depending on what you're doing.
l

lovis

06/27/2017, 7:58 AM
@Ruckus
Data classes are simple containers for encapsulating data, not functionality
i would not go so far and say “no functionality” there is a reason why you can add functions to data classes… using the
data
keyword is not an excuse to write an anemic model.
however, i argee that they probably shouldn’t have custom getters/setters though, since that breaks POLA
r

Ruckus

06/27/2017, 2:18 PM
I guess minimal functionality might have been better, but I actually go with no functionality for data classes. It makes it clearer to me when using a data class what I can and cannot expect from it, but that is obviously a personal preference.
👍 1