do kotlin data classes have no arg constructors? I...
# getting-started
c
do kotlin data classes have no arg constructors? I'm asking because of gson documentation "If you are using ProGuard or R8 (for example for Android projects) you might not need any special Gson configuration anymore if your classes have a no-args constructor and use @SerializedName for their fields."
c
Not by default, but nothing stops you from adding a secondary no-arg constructor. In general though, having a no-arg constructor means the class must be mutable, and data classes should rarely be mutable.
c
gotcha. i wonder if just adding @Keep would work
just weird that the gson docs mention 0 about it. lol
r
if the no-arg constructor is only needed because of some third-party library requiring it (like json (de)serializing libraries), you could use the no-arg compiler plugin to generate it for you
m
Excuse me if I'm being naive, but why shouldn't data classes be mutable? Looking at the kotlin docs I don't see anything suggesting that, in fact the contrary since it specifically mentions constructor parameters being marked as var not just val. What am I missing?
r
I think for certain cases there is nothing wrong with mutable data classes, but making a data class mutable just because some third-party library requires a no-arg constructor (even though the data should functionally be immutable) feels wrong 🙂
c
Because mutable data structures are hard to work with. See https://ivan.canet.dev/blog/2025/05/12/sets.html which is about mutable data structures (classes or otherwise) break sets
In general, we use
data class
when we want equals & hashCode, but equals and hashCode are broken for mutable classes, so mutable
data class
is in general a bad idea (but it's still allowed in case you really do know what you're doing) For more reading, see Effective Java by Joshua Blosch, items 10–12 (they apply to Kotlin too)
💡 1
a
Mutable data classes will bring nothing but huge misunderstanding in your team. Copy constructor should solve the issue with simple minor mutation
m
Many thanks
c
good topic on immutability from previous kotlin lead https://elizarov.medium.com/immutability-we-can-afford-10c0dcb8351d
👍 1
💯 1