请注意,这个问题与 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 设置中完全关闭它?
无关:如果您对课程的设计有任何其他建议,或者只是让您感到困扰,请随时对此帖子发表评论。我总是乐于改进某些东西。