[英]Set variables dynamically by passing parameters by reference in a Groovy closure
Is there a way I can set a variable by calling a closure in groovy? 有没有一种方法可以通过在Groovy中调用闭包来设置变量? VAR1 returns 2 but I would expect it to return the value in cell I2.
VAR1返回2,但我希望它返回单元格I2中的值。
def f_getdata = {ColDesc, ColNum ->
ColDesc = Float.parseFloat(sheet.getRow(1).getCell(ColNum).getRawValue())}
def VAR1 = 2
f_getdata(VAR1, 8)
The most of simple-like types (String, Integer, Long, ...) are non-changeable. 大多数类似简单的类型(字符串,整数,长整数,...)都是不可更改的。
So you can't do what you've described. 因此,您无法执行所描述的操作。
But if VAL1
will be in a container - for example Map
- then you can change values in the Map: 但是,如果
VAL1
将位于容器中(例如Map
,则可以在Map中更改值:
def ctx = [
VAL1:"world"
]
def f_getdata = {ColDesc, ColNum ->
ctx[ColDesc] = "hello "+ ctx[ColDesc]
}
f_getdata("VAL1", 8)
println ctx.VAL1
result: 结果:
hello world
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.