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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With