Axe Axe - 1 year ago 105
Groovy Question

Why two equivalent property are not equal in Groovy

Please have a look at this simple code:

String.metaClass {
getA = {delegate <<= delegate}

assert 'a'.a == 'a'.a

Result: Assertion failed:
assert 'a'.a == 'a'.a
| | |
| false aa

Why the result is FALSE?

I am working at Groovy 2.4.7 on Windows 7 SP1

Answer Source

LeftShift on a String in Groovy generates a StringBuffer (docs)

So 'a'.a == 'a'.a is trying to do equals on two StringBuffers.

You can't do that with StringBuffer as the equals method isn't overloaded, and just checks if they are the same instance

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download