Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-2503 MOP 2.0 design inflluencing issues
  3. GROOVY-3364

== operator does not work anymore if Comparable is implemented!

    XMLWordPrintableJSON

Details

    • Sub-task
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.5.7, 1.6-rc-3
    • None
    • groovy-runtime
    • None
    • Patch

    Description

      Once a class implements Comparable, the == operator does not work anymore!

      class X implements Comparable {
        int compareTo(Object object) {
          return 0
        }
        boolean equals(Object object) {
          return true;
        }
      }
      
      public void testEqualityOperator() {
        def x = new X()
        def y = new Y()
        assert x == x   // OK 
        assert x == y // OK 
        assert x == 1 // FAIL - Neither compareTo() nor equals() is called!
      }
      

      The location of the bug is in

      DefaultTypeTransform.compareToWithEqualityCheck(Object left, Object right, boolean equalityCheckOnly):
      
              if (equalityCheckOnly) {
                  return -1; // anything other than 0
              }
      

      The fix is:

              if (equalityCheckOnly) {
                return ((Boolean) InvokerHelper.invokeMethod(left, "equals", right)).booleanValue() ? 0 : -1;
              }
      

      An even better fix would be to always use equals for the == operator - but this is already discussed in other issues.

      I've set this to a BLOCKER beause this issue leads to the fact that I cannot use Groovy for relaxed typing - and that makes it useless for many DSLs!

      Attachments

        Activity

          People

            Unassigned Unassigned
            peter.rietzler@smarter-ecommerce.com Peter Rietzler
            Votes:
            10 Vote for this issue
            Watchers:
            12 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: