groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From paul <>
Subject map constructor for List<CustomObject> ?
Date Fri, 10 Nov 2017 11:04:32 GMT
Hi all,

I'm doing a little YAML-parsing where I have CustomObjects having Lists 
of other CustomObjects as properties, but the default map constructor 
does not seem to work for these lists.

class Sample {
   Integer age
   String name
class SampleCollection {
   String name
   List<Sample> listOfSamples
def m = [name:'Collection1',listOfSamples:[ 
[age:10,name:'Anna'],[age:12,name:'Berta'] ]]
def c = m as SampleCollection // or c = new SampleCollection(m)
assert c.class == SampleCollection // passes
assert c.listOfSamples[0].class == Sample // fails

First solution I've come up with is adding a custom constructor to 
SampleCollection like this:

   SampleCollection(Map map) {
     name =
//     listOfSamples = map.listOfSamples // cast not working
     listOfSamples = []
     map.listOfSamples.each{ sample ->
       listOfSamples << (sample as Sample)

This works, but seems rather inefficient, as
a) I have to loop through each list with potentially many items and
b) SampleCollection has some more simple properties like 'name', which I 
don't want to add all manually. Is there a way to use the default for 
these simple properties?

typed with Neo 2 -- an ergonomically optimized keyboard layout
for German, English, programming, and science

View raw message