Groovy 覆盖 compareTo

Sta*_*sky 6 dsl groovy

我正在使用 Groovy 类别的 DSL 下工作,我需要覆盖/重载==运算符。然而,已知的问题是,当类实现时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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在当我跑

use(BaseCategory) {
    Base a = new Base(1, 2)
    Base b = new Base(1, 3)
    println a == b
    println a <=> b
}
Run Code Online (Sandbox Code Playgroud)

我得到了trueand 0,而不是falseand -1。有什么解决方法吗?

Wil*_*ill 5

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和测试:

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
Run Code Online (Sandbox Code Playgroud)