groovy

operator overloading for comparisons does not work if right operand is a Number

Details

  • Type: Bug Bug
  • Status: Closed Closed
  • Priority: Minor Minor
  • Resolution: Fixed
  • Affects Version/s: 1.0-JSR-6
  • Fix Version/s: None
  • Component/s: None
  • Labels:
    None
  • Number of attachments :
    0

Description

Implementing the Comparable interface and therefore the method compareTo() should allow overloading for comparison operators. But as soon as the right operand of the comparison is an instance of Number, the Invoker tries to convert the left operand to a Number using the method asNumber(). The conversion method asNumber() however only supports instances of String, Character or Number, otherwise an exception is thrown. So in this case the method compareTo(), which in fact might be able to handle the comparison for Number instances fairly well, gets never called. My suggestion is to test the left operand first, if it can be converted to a number to avoid the exception and call the compareTo() in all other cases.

Activity

Hide
blackdrag blackdrag added a comment -

testing this:

class X implements Comparable {
  int compareTo(Object x) {0}
}
def x = new X()
assert x<=>1 == 0
I get no error as expected.

Show
blackdrag blackdrag added a comment - testing this:
class X implements Comparable {
  int compareTo(Object x) {0}
}
def x = new X()
assert x<=>1 == 0
I get no error as expected.

People

Vote (0)
Watch (0)

Dates

  • Created:
    Updated:
    Resolved: