Michal Kordas Michal Kordas -4 years ago 174
Groovy Question

Why I cannot get exactly the same GString as was put to map in Groovy?

With the following snippet I cannot retrieve

from a map:

def contents = "contents"
def gString = "$contents"

def map = [(gString): true]

assert map.size() == 1 // Passes
assert gString.hashCode() == map.keySet().first().hashCode() // Passes, same hash code
assert gString.is(map.keySet().first()) // Passes, exactly the same object
assert map[gString] // Fails

How is that possible?

What's interesting here is that
works fine while
does not.

Assertion message clearly shows that there's something wrong:

assert map[gString] // Fails
| ||
| |contents
| null

It's not the same question as Why groovy does not see some values in dictionary?
First answer there suggests:

You're adding GString instances as keys in your map, then searching for them using String instances.

In this question I clearly add
and try to retrieve

Also neither Why are there different behaviors for the ways of addressing GString keys in maps? nor Groovy different results on using equals() and == on a GStringImpl have an answer for me. I do not mutate anything and I do not mix
. Groovy documentation is not helpful as well.

Answer Source

tl;dr: You seem to have discovered a bug in Groovy's runtime argument overloading evaluation.


map[gString] is evaluated as map.getAt(gString) at runtime straightforwardly via Groovy's operator overloading mechanism. So far, so good, but now is where everything starts to go awry. The Java LinkedHashMap class does not have a getAt method anywhere in it's type hierarchy, so Groovy must use dynamically associated mixin methods instead (Actually that statement is sort of reversed. Groovy uses mixin methods before using the declared methods in the class hierarchy.)

So, to make a long story short, Groovy resolves map.getAt(gString) to use the category method DefaultGroovyMethods.getAt(). Easy-peasy, right? Except that this method has a large number of different argument overloads, several of which might apply, especially when you take Groovy's default argument coercion into account.

Unfortunately, instead of choosing DefaultGroovyMethods.getAt(Map<K,V>,K), which would seem to be a perfect match, Groovy chooses DefaultGroovyMethods.getAt(Object,String), which coerces the GString key argument into a String. Since the actual key is in fact a GString, the method ultimately fails to find the value.

To me the real killer is that if the dynamic overload resolution occurs before the operator resolution and the category method selection, then Groovy makes the right overload choice! If you replace this expression:


with this expression:


then the argument overloading is resolved correctly, and the correct value is found and returned.

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