groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Anthony Hepple <>
Subject Re: map constructor for List<CustomObject> ?
Date Tue, 21 Nov 2017 15:31:46 GMT
> Nevertheless I'd be interested in WHY the list-entries are not cast
> automagically. Does Groovy even check the <T> type of list elements, or
> just ignores it?
> If someone can give me some insights, that would be much appreciated.

As far as I understand it, Groovy ignores all generic type declarations.
Generics are syntactically valid Groovy only to support copy/paste of Java
Automagic casting would involve recursive assignment of properties during
groovy's map construction process. Instead the map construction process
calls the default constructor followed by the setters indicated by the
map's keys.

def c = new SampleCollection(name: 'collection1', listOfSamples: [[age: 10,
name: 'Anna'],...])

Is executed as;

GroovyObject c = new SampleCollection();
c.setListOfSamples([[age: 10, name: 'Anna'],...]);

[[age: 10, name: 'Anna'],...] is a list literal it is assigned (as an
ArrayList object) to the listOfSamples property.
[age: 10, name: 'Anna'] is a map literal which becomes a LinkedHashMap
object and at no time (until you introduce the custom setter) is it cast to
a Sample object.

Unless overridden with a custom setter, the generated setter is a simple
assignment of argument to property. Eg. ArrayList -> List

Hope this helps.

View raw message