In Groovy, when I call a map constructor, e.g.
new Player(name:'Lionel', surname:'Messi', number: 10, team:barcelona)
how do I know the order in which property setters will be called?
I need to know this because I need to apply certain logic in some of my setters, and I need to know which data will be set in the object when each setter is called.
With a quick script, it seems that they are set in the order that are passed:
However, you can understand more about what Groovy is doing by following the code with a debugger. If you put a breakpoint in one of the setters in that code, you’ll notice that the call-stack includes
MetaClassImpl.setProperties, which means that these properties are being set by that method. If we take a look atsetProperties‘ code we can confirm that it is using the map iterator to traverse the map that is passed in the constructor. And, as Groovy uses LinkedHashMaps, which are ordered, as the default Map implementation, we can conclude that those properties will be set in the order that they are defined in the constructor’s map 🙂