2

I imagine I'm screwing something up with these declarations, but I've got a groovy class with a field defined like this:

Map<String, SomeType> _someField = [:]

I do inserts like this:

_someField.put( someStringVariable, someTypeInstance )

...and then later, when I check whether a key I know has been mapped is present, the check fails:

_someField.containsKey( someStringVariable )

The only way I can get this to succeed is by calling toString(), like so:

_someField.containsKey( someStringVariable.toString() )

I'm using the generic declaration of the map so my IDE gives me auto completion on the value types, so I'd really like (I think) to keep the type information there.

I've tried changing the key type from String to GString, but to no avail. I've tried changing the map initialization from the groovy shorthand [:] to new LinkedHashMap<>, also to no avail.

Any ideas whether I can keep the type information and avoid having to use toString()?

Hoobajoob
  • 2,748
  • 3
  • 28
  • 33

1 Answers1

3

So this was a case where the variable being fed to containsKey() in the instances where it is failing were of type org.codehaus.groovy.runtime.GStringImpl because they were generated by a function that was performing variable expansion on map values, and that function was creating groovy interpolated strings for values instead of Java Strings.

A quick check on the type of the variable confirmed the type problem, and then it was just a matter of tracking back to find the source of the interpolated string.

Hoobajoob
  • 2,748
  • 3
  • 28
  • 33
  • I am completely unaware of the problems found and design decisions taken by the groovy staff, and I assume they have found and solved multiple problems that I can't even imagine. This said: couldn't the problem in hand be easily solved by rewriting the 'hashCode' method of GString to match the value of the equivalent String? – Jorge_B Apr 02 '18 at 08:56