简体   繁体   English

如何遍历Class类型的列表以在Groovy中编辑其对象的属性

[英]How to iterate over a list of type Class to edit the properties of its objects in Groovy

I know there are more elaborate ways to achieve this in Java, but Groovy should have a concise way to do the same as per http://groovy.codehaus.org/Looping 我知道在Java中有更多精心制作的方法可以实现这一点,但是Groovy应该有一种简洁的方法来完成与http://groovy.codehaus.org/Looping相同的操作

Class Currency.groovy 类Currency.groovy

class Currency {
    String name
    double rate
}

CurrencyController CurrencyController

def select(){
    List<Currency> selectedCurrencies = Currency.getAll(params.currencies)
    selectedCurrencies.eachWithIndex { obj, i -> obj.rate = update(obj.name)};
    [selectedCurrencies:selectedCurrencies]
}

def update(String sym){
    return sym
}

The above code throws: 上面的代码抛出:

No signature of method: currencychecker.CurrencyController$_$tt__select_closure12.doCall() is applicable for argument types: (currencychecker.Currency)

Thanks to @dmahapatro, the issue was that I was using an iterator variable obj[i] , even though obj itself is the iterated object. 感谢@dmahapatro,问题是我使用了迭代器变量obj[i] ,即使obj本身就是迭代对象。 The rest is correct! 其余的是正确的! I experimented with selectCurrencies.each as well instead of selectCurrencies.eachWithIndex however the right one in this case is eachWithIndex 我也尝试了selectCurrencies.each而不是selectCurrencies.eachWithIndex但是在这种情况下,正确的方法是eachWithIndex

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

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