ITADN

Incorrect equals(/hashcode) implementation for data classes with inheritance

#419ClosedMahnas92 创建于 2025-04-10
M
Mahnas92commented
A bug occurs for a Kotlin data class with inheritance caused by incorrect behavior in equals() and hashCode() implementations. When a data class extends another class, Kotlin automatically generates these methods based only on the properties declared in the subclass, ignoring properties in the base class. This results in incorrect equality comparisons and hash codes, which can break collections (like Set or Map), cause subtle logic bugs, and violate the contract of equals() and hashCode(). **Impact:** Equality checks between logically equal objects may fail. Hash-based collections may behave unpredictably. Bugs may be difficult to trace in applications relying on polymorphic data models. **Proposed Fix:** I think Kotlin should add a condition that checks that the two instances' super classes is also equals in the auto-generated equals fun.
关闭于 2025-04-10 1 条评论