我正在使用 Groovy 类别在 DSL 下工作,我需要覆盖/重载==
操作员。然而却是已知问题 http://jira.codehaus.org/browse/GROOVY-3364,当类实现Comparable
, Groovy 会调用compareTo()
方法用于==
操作员。我正在寻找一些解决方法(不是 AST 转换)以便==
做我想做的事。
我有以下“玩具”情况:
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;
}
}
现在当我跑步时
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
, 代替false
and -1
。有什么解决方法吗?
An old Groovy bug[1] https://jira.codehaus.org/browse/GROOVY-1765[2] http://jira.codehaus.org/browse/GROOVY-1888 to be fixed in 3.0. Does your use case permit encapsulation and delegation?
class Base implements Comparable<Base>{
int a, b
@Override int compareTo(Base o) {
return a <=> o.a
}
}
class BaseDelegate {
@Delegate Base base
boolean equals(o) {
if (o == null)
throw new NullPointerException()
if (o.getClass() != base.getClass())
return false
return base.a == o.a && base.b == o.b
}
int compareTo(o) {
int c = base.a <=> o.a;
if (c != 0)
return c
return base.b <=> o.b;
}
}
和测试:
def a = new Base(a: 1, b: 2)
def b = new Base(a: 1, b: 3)
assert (a == b) == true
assert (a <=> b) == 0
def a1 = new BaseDelegate(base: a)
def b1 = new BaseDelegate(base: b)
assert (a1 == b1) == false
assert (a1 <=> b1) == -1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)