在实现 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 (将#修改为@)