7 ms·
Java does equals and hashCode horribly. Granted, they did not have Java to learn from but it's what we have. Kotlin and Scala solve the problem pretty decently
by dtech 8y ago
Java does equals and hashCode horribly. Granted, they did not have Java to learn from but it's what we have.
Kotlin and Scala solve the problem pretty decently. Equals and hashCode are automatically generated for data/case classes. I've never encountered a messed up equals in Scala and only very rarely felt the need to override the generated equals, and then you make a very conscious choice to do it.
C# does it even better, there is a IEquatable<T> interface that defines the `bool Equals(T other)` method. It partially solves the irritating universal equality.
If I would design Java today Object would have no methods and there would be a stdlib interface defining `equals(other: T)`, and data classes would automatically implement that interface
- naasking 8y ago> If I would design Java today Object would have no methods and there would be a stdlib interface defining `equals(other: T)`, and data classes would automatically implement that interface This polymorphic equality is the default in some functional languages, like OCaml. It's fine for simple cases, but you really do need overloadable equality. Equality as a method in OO is a problem because of the asymmetry though, and often an even bigger problem because such languages typically permit pervasive null.
- dtech 8y agoThere definitely are cases where that's not enough, but it's a 95-99% solution. The problems you mentioned: Classes could change equals to accept subclasses. Then subclasses could not alter equality themselves. T implementing `equals(other: U)` for some U solves a lot of other use-cases, but could make equality asymetrical. Reference equality would still exist, but would not be the default, e.g. Java's `equals` is Scala's `==`, and Java's `==` is Scala's `eq` operator (which you almost never use)
- naasking 8y agohttps://blog.janestreet.com/the-perils-of-polymorphic-compare/ https://blog.janestreet.com/the-perils-of-polymorphic-compar...