Groovy set .each behavior for my class

I have a class in my project with a list defined in it. Is it possible to specify each(and all subsequent related methods, such as eachWithIndex) to use this List.

The only possible solution that I see is to make my class extended List, which I would rather not do.

+4
source share
1 answer

You can use @Delegate, as shown below, that delegates these method calls List:

class Test {
    @Delegate List myList
}

new Test(myList: [1, 2, 3]).each { println it }

new Test(myList: ['a', 'b', 'c']).eachWithIndex { val, index -> 
    println "$val at $index" 
}
+4
source

All Articles