0

Well, actually after checking GString.equals() method implementation it's not a mystery why it works as it works.

public boolean equals(Object that) {
    if (that instanceof GString) {
        return equals((GString) that);
    }
    return false;
}

The question remains, is it desired behaviour, shouldn't it return true by design in this case?

With the false in place it's easy to run into quite unexpected behaviour like:

"${'1'}" in ['1', '2', '3']

...is going to return false.

Is the current behaviour a result of equals and hashCode consistency contract or could it be improved to return more accurate results?

topr
  • 4,482
  • 3
  • 28
  • 35
  • So what happens with `"${-> val}"`? `val` can be late-bound then.. But until it is bound, the String representation of the Groovy String will throw an exception. – tim_yates Apr 18 '16 at 12:13
  • Basically, Groovy Strings are not Strings. – tim_yates Apr 18 '16 at 12:18
  • Also, http://docs.groovy-lang.org/latest/html/documentation/index.html#_gstring_and_string_hashcodes – tim_yates Apr 18 '16 at 12:20
  • Well, I'm fully aware that those are instances of a different class. Regarding the lazy one it should just throw exception as it does right now if it's not bound yet. The crucial thing though is the documentation link you posted and the doubt I expressed in the very last sentence of my question. It seems that equals - hashCode contract was violated here unless GString and String with the same content would have the same hash code. – topr Apr 19 '16 at 15:43

1 Answers1

0

It has been argued whether this is a bug or just "how it works"; however, it has been around for a while. What you are running into is that you are comparing a String and a GString, which are not equivalent with the same content. I had thought this behavior was modified in the current release of Groovy, but I could be wrong.

You can use the following to get the desired behavior:

("${'1'}" as String).equals('1')

This will also bite you when you use GStrings as keys in a Map or values in a Set.

cjstehno
  • 13,468
  • 4
  • 44
  • 56