solstice333 solstice333 - 4 years ago 118
Groovy Question

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

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?

Answer Source

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.

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