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
The problem is the increment and decrement methods of the
Overloadinstance.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 overridedtoStringmethod.Check now: