微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在实现 Comparable (Groovy) 的类中使用“==”时防止警告“GrEqualsBetweenInconvertibleTypes”

如何解决在实现 Comparable (Groovy) 的类中使用“==”时防止警告“GrEqualsBetweenInconvertibleTypes”

请注意,此问题与 Groovy('==' 表示相等而不是同一性)和 IntelliJ IDEA(但我不认为此问题特定于 IDE)有关。

我有一个类实现如下可比性:

class Money implements Comparable {
    BigDecimal value
    static final RoundingMode rounding = RoundingMode.HALF_UP

    Money(String stringValue) {
        if (stringValue) {
            this.value = roundToCent(new BigDecimal(formatString(stringValue)))
        } else {
            this.value = roundToCent(new BigDecimal(0))
        }
    }

    int compareto(Money money) {
        return this.value <=> money.value
    }
    
    int compareto(String string) {
        return this.value <=> roundToCent(new BigDecimal(string))
    }
    
    // I am aware equals methods aren't called here because compareto is used on Comparables,// however I figured it might give a better view of the issue.
    boolean equals(Money money) {
        def result = true
        if (money == null) {
            result = false
        } else if (this.value != money.value) {
            result = false
        }
        return result
    }
    boolean equals(other) {
        def result = true
        if (other == null) {
            result = false
        } else  {
            try {
                if (this.value != roundToCent(new BigDecimal(other))) {
                    result = false
                }
            } catch(ignored) {
                result = false
            }
        }
        return result
    }

    static String formatString(String string) {
        return string.replaceAll(/[^\d.]/,'')
    }

    static BigDecimal roundToCent(BigDecimal decimal) {
        return decimal.setScale(2,rounding)
    }

    static Money roundToCent(Money money) {
        money.value = roundToCent(money.value)
        return money
    }

    // Omitting methods not required for reproduction

}

所以在这种情况下,new Money('10.00') == '10' 可以完美地编译和运行,但我仍然收到“GrEqualsBetweenInconvertibleTypes”编辑器警告:'==' between objects of inconvertible types 'Money' and 'String'

直接问题:有没有办法在 Groovy 中构造类或方法来避免此警告,而不必在 IDE 设置中完全关闭它?

无关:如果您对类的设计有任何其他建议,或者只是打扰您,请随时对此帖子发表评论。我总是乐于改进某些东西。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。