Groovy - GString being used as key versus String as key, subscript notation versus put method
Asked Answered
J

1

5

In the groovy documentation, it mentions that using a GString for a key is bad:

def key = 'some key'
def map = [:]
def gstringKey = "${key.toUpperCase()}"
map.put(gstringKey,'value')
assert map.get('SOME KEY') == null

However, simply changing the put() method to use subscript notation:

def key = 'some key'
def map = [:]
def gstringKey = "${key.toUpperCase()}"
map[gstringKey] = 'value' // here
assert map.get('SOME KEY') == null

is enough to cause the assert to fail. How are the semantics any different between using [] and the put() method? Does subscript notation have some sort of implicit cast to String maybe?

Jaeger answered 1/2, 2017 at 23:17 Comment(0)
S
7

Does the subscript notation have an implicit cast to String?

Basically, yes.

The statement a[b] = c is equivalent to calling the a.putAt(b, c) method, as per the Groovy operator overloading rules.

The specific signature of the putAt method is void putAt(String property, Object newValue), which means that if b is a Groovy String, it will first be converted to a String using its toString() method.

Ultimately, the putAt method will call Map.put using the String value as the key.

Stokehold answered 2/2, 2017 at 4:56 Comment(1)
I don't understand the problem with using a GString as a map key with subscript notation. The conversions to a String is probably what one would want anyway. The Groovy documentation should instead warn against using the get and put methods of Map.Chiasmus

© 2022 - 2024 — McMap. All rights reserved.