加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy覆盖compareTo

发布时间:2020-12-14 16:22:18 所属栏目:大数据 来源:网络整理
导读:我使用Groovy类在DSL下工作,我需要覆盖/ overload ==运算符.但是 known issue,当类实现Comparable时,Groovy将为==运算符调用compareTo()方法.我正在寻找一些解决方法(不是AST转换),以使==做我想要的. 我有以下“玩具”情况: class Base implements Comparab
我使用Groovy类在DSL下工作,我需要覆盖/ overload ==运算符.但是 known issue,当类实现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
}

我得到了0和0,而不是假和-1.有没有解决方法?

解决方法

一个旧的Groovy bug [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;
    }
}

测试:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读