在构造函数中使用动态变量

时间:2017-05-16 16:44:45

标签: variables groovy constructor

我总是在代码的不同部分花费成本A和类似的变量,我感兴趣的是如何使用#34; Groovy Magic"

使这更容易/更快
def class Test{

    int costA
    int costB
    int costC
    int costD
    int costE

    Test(int A, int B, int C, int D, int E)
    {
        ['A'..'E'].flatten().each
        {
             (this."cost${it}"="${it}") //does not work as expected
        }
    }

}

​Test test = new Test(1,2,3,4,5) ​​​​​​

['A'..'E'​​​​​​​​​].flatten().each​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​{​​println(test."cost${it}")}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

结果:

65  // 'A' etc.
66
67
68
69
70

它的第一部分有效,所以这样就可以了

 this."cost${it}"=1 

但是"${it}"只是转换为A等而不是A中的值。this."${it}"显然会给我错误的变量,但我怎么能说服groovy使用构造函数的值给了谁?

(我尝试了args."${it}"args[0]等,但它没有工作)

Bonusquestion(但不那么重要):为什么我需要展平['A'..'E']以获得包含这5个字符的列表? Aka会有更清洁/更短的方式来获得相同的清单吗?

2 个答案:

答案 0 :(得分:0)

这个怎么样?

地图

def map = [costA:50, costB: 60, costC: 70, costD: 80, costE: 90]
map.collect{k, v -> println " ${k} is ${v}"}

展开动态Bean

def map = new Expando(costA:50, costB: 60, costC: 70, costD: 80, costE: 90)
map.properties.collect { k, v -> println "${k} is ${v}" }

答案 1 :(得分:0)

我认为使用列表(http://groovy-lang.org/groovy-dev-kit.html)是最好的方法:

所以你可以把你的班级作为:

class Cost {

    def amount
    def description

    def asString() {
        description + ': $' + amount // returns 'potatoes: $1.00'
    }

}

class CostsReport {

    List<Cost> costs

    def report() {
        costs.each { c -> println(c.asString() + '\n') } // prints out all your costs
    }

}