In my opinion, data classes in Kotlin should not be used unless you really understand what you are doing.
Overriding equals
/hashCode
on mutable data can cause a problem.
Consider you have added instance of a mutable class to HashSet
, then changed some if properties of that instance.
This affects value returned by hashCode
.
In turn, this makes it impossible for HashSet
to find the instance, since it will look for it in completely different hashtable entry.
You won't be able to remove this instance from HashSet
!
Good examples of candidates to be data classes in kotlin are: complex numbers, constant-sized vectors.
Bad examples are: JPA entities, DTOs.
As for JPA, these articles are opinionated.
There's another opinion: you should not override equals
and hashCode
for JPA entities at all.
Rationale: JPA providers (Hibernate, EclipseLink) must guarantee that a === b
iff a and b have the same primary key in table, and both a and b are in persistent state.
This contract may be broken for detached entities.
But, in my opinion working with detached entities is a bad practice that one should avoid.
This only thing that may have sence is to store detached entities to merge them in another JPA transaction.