I am working under DSL using Groovy categories and I need to override/overload == operator. It is however known issue, that when class implements Comparable, Groovy will call compareTo() method for == operator. I'm looking for some workaround (not AST transformation) in order to make == do exactly what I want.
I have the following "toy" situation:
class Base implements Comparable<Base>{
int a, b
Base(int a, int b) {
this.a = a
this.b = b
}
@Override
int compareTo(Base o) {
return a <=> o.a //compare only a
}
}
class BaseCategory {
static boolean equals(Base base, o) { //complete equals
if (o == null)
throw new NullPointerException()
if (o.getClass() != base.getClass())
return false
return base.a == o.a && base.b == o.b
}
static int compareTo(Base base, o) { //compatible with equals
int c = base.a <=> o.a;
if (c != 0)
return c
return base.b <=> o.b;
}
}
Now when I run
use(BaseCategory) {
Base a = new Base(1, 2)
Base b = new Base(1, 3)
println a == b
println a <=> b
}
I got true and 0, instead of false and -1. Is there any workaround?
equalsmethod calls yourhashCodemethod directly, which is not a great idea, but may not be the problem you are concerned with. ThehashCodemethod method is just returning2 * asobis irrelevant. Is that really what you want? - Jeff Scott Brownequals()andcompareTo()more carefully, the result will be the same. - Stanislav Poslavsky