Groovy覆盖compareTo

Groovy覆盖compareTo,第1张

概述我使用Groovy类在DSL下工作,我需要覆盖/ overload ==运算符.但是 known issue,当类实现Comparable时,Groovy将为==运算符调用compareTo()方法.我正在寻找一些解决方法(不是AST转换),以使==做我想要的. 我有以下“玩具”情况: class Base implements Comparable<Base>{ int a, b 我使用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) == trueassert (a <=> b) == 0def a1 = new BaseDelegate(base: a)def b1 = new BaseDelegate(base: b)assert (a1 == b1) == falseassert (a1 <=> b1) == -1
总结

以上是内存溢出为你收集整理的Groovy覆盖compareTo全部内容,希望文章能够帮你解决Groovy覆盖compareTo所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1220427.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存