I work under DSL using Groovy categories and I need to override / reload the ==statement. However, the known problem is that when the class implements Comparable, Groovy will call the method compareTo()for the statement ==. I am looking for some solution (not AST conversion) to ==do exactly what I want to do.
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
}
}
class BaseCategory {
static boolean equals(Base base, o) {
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) {
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 trueand 0instead of falseand -1. Is there a workaround?
source
share