这是我想要做的:
我有一个名为的类RowCollection
,它包含一个Row
对象集合,带有一个名为 的方法edit
,它应该接受另一个对对象进行操作的方法(或闭包)作为参数Row
。
groovy 脚本将通过以下方式使用此类的对象:
rc.edit({ it.setTitle('hello world') }); // it is a "Row" object
我的问题:
- 的签名
RowCollection#edit
会是什么样子? - 它的实现是什么样的?
作为替代方案,如果您RowCollection
实现Iterable<Row>
并提供合适的iterator()
方法,那么适用于所有类的标准 Groovy-JDK 魔法将启用
rc.each { it.title = "hello world" }
并且您以相同的方式免费获得所有其他支持的iterator
GDK 方法,包括collect
、findAll
、inject
、和.any
every
grep
好的 - 稍微挖掘一下,这里是:
class RowCollection {
private List<Row> rows;
// ...
public void edit(Closure c) {
for(Row r : rows) {
c.call(r);
}
}
// ...
}
类 Closure 在groovy.lang
包中。