jmq
jmq

Reputation: 10370

Groovy Operator Overloading Increment/Decrement Error

I have the following Groovy code snippet that is attempting to use operator overloading for increment, decrement and equals. All this does is create two instances, perform the increment and a decrement one one of the instances and then compare the two instances using the overloaded methods equals. When I do the comparison it fails. Both should be 100 when this code completes. (the print statements show it, but one of the toString() functions appear to be wrong). What am I doing wrong here?

This is with groovy 1.8.6

class Overload {
    def value

    public Overload(value = 0) {
        this.value = value
    }

    def next() {
        value = value + 1;
    }

    def previous() {
        value = value - 1;
    }

    def boolean equals(other) {
        if (value == other?.value) {
            return true
        }

        return false
    }

    def String toString() {
        "value is = ${value}"
    }
}

def cls1 = new Overload(100)
def cls2 = new Overload(100)

cls1++
cls1--
if (cls1 == cls2) {
    println("cls1 == cls2")
}
else {
    println("cls1 != cls2")
}

println(cls1.toString())
println(cls2.toString())

Output:

cls1 != cls2
100
value is = 100

Upvotes: 2

Views: 1930

Answers (2)

tim_yates
tim_yates

Reputation: 171144

As a quick additional comment, you don't need to be using def when defining the return type of your methods. A cleaner version of your class is:

class Overload {
    def value

    public Overload(value = 0) {
        this.value = value
    }

    def next() {
        value = value + 1
        this
    }

    def previous() {
        value = value - 1
        this
    }

    boolean equals(other) {
        value == other?.value
    }

    String toString() {
        "value is = ${value}"
    }
}

Upvotes: 1

Arturo Herrero
Arturo Herrero

Reputation: 13122

The problem is the increment and decrement methods of the Overload instance.

Groovy has the feature of implicit return for the last expression evaluated. When you call to cls1++, now the object is an Integer, that's the reason we not see the output from the overrided toStringmethod.

def next() {
    value = value + 1
    return this
}

def previous() {
    value = value - 1
    return this
}

Check now:

assert cls1.class == Overload
assert cls2.class == Overload
assert cls1 == cls2
assert cls1 == 100
assert cls2 == 100

Upvotes: 6

Related Questions