3 ms·
This doesn't really solve the ambiguity. You can do the same in Java (and people often do): if (getClass() != other.getClass()) return false; This do
by dnomad 8y ago
This doesn't really solve the ambiguity. You can do the same in Java (and people often do):
if (getClass() != other.getClass())
return false;
This does guarantee that equality is symmetric but it's also troublesome. First, you have to trust everybody to do this comparison. If one type forgets then symmetry breaks. But also, sometimes, in the case of value objects like Points you do want equality between different types. Point2D and Point3D and RasterPoint all have x,y coordinates and should be equatable.
The proposal is to capture equality (and all other operators) as static methods.
class Point2D {
public static boolean operator_equals(Point2D p1, Point2D p2) { ... }
}
class ColoredPoint {
public static boolean operator_equals(ColoredPoint cp, Point2D p2) { ... }
}
In certain cases the compiler can unambiguously determine that there is a single static method that defines equality then this can be invoked by 'a == b' and we can also be sure that 'b == a' because both refer to the same method.
The point here is that equality is not something that can be decided by one object, it is an operator that establishes relations between types of objects. There's a very fundamental difference between sending a message to a single object and establishing a relation and this is the source of all the confusion around equality.