简体   繁体   中英

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? VAR1 returns 2 but I would expect it to return the value in cell 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:

def ctx = [
    VAL1:"world"
]
def f_getdata = {ColDesc, ColNum -> 
    ctx[ColDesc] = "hello "+ ctx[ColDesc]
}
f_getdata("VAL1", 8)

println ctx.VAL1

result:

hello world

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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