I have a problem with maps and I like some input from Groovy experts to
understand if it's a bug in my Groovy script or a bug in Groovy.
I use the subscript syntax for accessing elements in a map, as in:
def things = [:]
things['mything'] = 1
println things['mything']
I recently upgraded a script from Groovy 3.0.10 to Groovy 5.0.5 and my script
broke because it happened to use a key named "properties". In this case, the
keys are determined programmatically and represent the names of internal
libraries. I was able to fix my script by using the methods of Map: put(),
get(), but that feels ungroovy and I'd like to continue using the subscript
syntax.
This can be seen in groovysh from Groovy 5.0.5
groovy> map = [:]
groovy> map['properties'] = 1
ReadOnlyPropertyException: Cannot set read-only property: properties for
class: java.util.LinkedHashMap
groovy> map['properties']
[:]
Whereas I expect behavior similar to what I see in Groovy 3.0.10, where
map['properties'] can be used to add and read an element.
groovy:000> map = [:]
===> [:]
groovy:000> map['properties'] = 1
===> 1
groovy:000> map['properties']
===> 1
The documentation for Map at
https://groovy-lang.org/groovy-dev-kit.html#_adding_or_removing_elements_2 says
that elements can be added with the subscript operator, so I didn't think I was
doing anything wrong.
Am I wrong to use the subscript operator if I don't know for sure that my keys
won't conflict with a property of Map? Or is this a bug in Groovy 5.0.5?
-David Costanzo