So if you'd like to expand on why it is better to ...
# getting-started
a
So if you'd like to expand on why it is better to create a non-data class and override those methods myself, please do as I would love to understand it. If not, that's okay too, I trust you on that one even though that won't stop me from wishing there was an annotation I could use to request those overrides anyway 😛
r
angarron: The idea behind data classes was a more consise way to write POJOs, that is, classes with just properties, simple getters and setters, and equals/hashCode/toString. Basically, they were meant to represent chunks of data. Once you start adding logic and functionality, it's no longer just data, so you should use a normal class.
In your case, the
ManageUserHelper
may be a great option for a data class. But performing logic on objects to derive the data that goes into the class isn't the responsibility of the data, and thus not the responsibility of the data class's constructor. That code would be better suited in a function, possibly on the companion object. The constructor of a data class should just take the data it's meant to carry.
a
Cool, makes perfect sense.
I don't actually have an issue with data classes at all. The only (minor) pain point for me is the lack of a way to request that the compiler generates
equals
,
hashCode
, and
toString
on any class as those are somewhat time-consuming to write (and easy to forget to change if you add a new field), but as you have mentioned, sometimes you wanna do things during initialization that go beyond the scope of what a data class typically wants to do.
(That use case, though, is rare, and already has suitable workarounds like the
operator fun invoke
that you showed me to have something of a virtual constructor. So I am very satisfied overall 🙂 and again, huge thanks!!)
r
There are potential edge cases to worry about when you let the compiler generate that code. What about a class that subclass that class? Especially with the way Kotlin allows property delegates to override, there could be all sorts of issues. Data classes can't be subclassed, so they don't need to worry about it.
a
Good point about subclassing! Lombok (which if I never saw in my codebase again, I would be all too happy) gets around that by specifying whether the superclass should influence the subclass's generated methods, but I always found that hamfisted. I think I understand some of the concerns now, thanks!
👍 1