Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

groovy

gstring

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?

like image 221
solstice333 Avatar asked Feb 01 '17 23:02

solstice333


1 Answers

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.

like image 110
bdkosher Avatar answered Nov 10 '22 12:11

bdkosher