gpt4 book ai didi

Groovy 覆盖 compareTo

转载 作者:行者123 更新时间:2023-12-01 02:16:06 27 4
gpt4 key购买 nike

我正在使用 Groovy 类别在 DSL 下工作,我需要覆盖/重载 ==运算符(operator)。然而,它是 known issue ,当类实现 Comparable , Groovy 将调用 compareTo() == 的方法运算符(operator)。我正在寻找一些解决方法(不是 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
}

我得到了 true0 , 而不是 false-1 .有什么解决方法吗?

最佳答案

一个旧的 Groovy 错误 [1] [2]将在 3.0 中修复。您的用例是否允许封装和委托(delegate)?

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

关于Groovy 覆盖 compareTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24963680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com