Note that this question pertains to Groovy ('==' means equality rather than identity) and IntelliJ IDEA (but I don't believe this issue to be IDE-specific).

I have a class that implements comparable below:

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

}

So in this case, new Money('10.00') == '10' compiles and runs perfectly, but I still get the 'GrEqualsBetweenInconvertibleTypes' editor warning: '==' between objects of inconvertible types 'Money' and 'String'.

Direct question: Is there a way to structure the class or method in Groovy to avoid this warning without having to turn it off altogether in the IDE settings?

Unrelated: if you have any other suggestions for the design of the class, or if it just bothers you, feel free to comment on this post about it. I'm always open to improving something.

0

There are 0 best solutions below