continued the discussion <here>. `data class` has...
# getting-started
y
continued the discussion here.
data class
has a feature where you opt-out of automatic generation of
equals()
(etc.) by moving a property outside of the primary constructor... this (imo) is a good feature. but
copy()
prohibits a non-public primary constructor for a
data class
, so how do you even exclude anything that needs to be set at init? do I really need to fall back to manual implementation any time I have such a property? you can use a default value for such properties (or even
lateinit var
), and initialize them to a non-default value via a secondary constructor. but since the primary constructor is public this seems rather error-prone.
or is this working as expected, as anything included in the public constructor is "public API" and thus must be used to "differentiate" between two instances of a
data class
?
l
I think if you need this much control, you probably shouldn't be using a data class in the first place. Just use a normal class.
y
that's debatable, but this is more of a question of, doesn't "keep fields out of primary constructor to opt-out of autogeneration" and "you can't have a non-public primary constructor because `copy()`" go in opposite directions, design-wise?
l
Yes, I think so. They could certainly be designed better. I think data classes are nice if you what you need is exactly what it provides. Otherwise you're better off just doing it yourself.
thank you color 1
k
Also, note that some time in the future (maybe Kotlin 2.3) if you have a private constructor then the
copy
function will also be private.
y
@Klitos Kyriacou that is a good change and makes a lot of sense to me.
and I assume you can then make a custom
copy
-like function and delegate to the private one.
v
my experience is that the moment
data class
doesn't do exactly what you want, just use
class
and you will be better off yes, they could have designed them better, I think they were a bit rushed and are probably very hard to evolve at this point
l
Indeed. To be honest, they feel a bit superfluous.