简体   繁体   English

Groovy为我的班级设置.each行为

[英]Groovy set .each behavior for my class

I have a class in my project with a List defined in it. 我的项目中有一个类,其中定义了一个List。 Would it be possible to point each (and all subsequent related methods such as eachWithIndex ) to use that List. 是否可以指向each (以及所有后续相关方法,例如eachWithIndex )来使用该List。

The only possible solution I can see would be to make my class extend List , which I would rather not do. 我能看到的唯一可能的解决方案是让我的类扩展List ,我宁愿不做。

You can use @Delegate transformation as below which delegates those method calls to List : 您可以使用下面的@Delegate转换将这些方法调用委托给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" 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM