【问题标题】:Set variables dynamically by passing parameters by reference in a Groovy closure通过在 Groovy 闭包中通过引用传递参数来动态设置变量
【发布时间】:2018-11-23 18:34:18
【问题描述】:

有没有办法通过在 groovy 中调用闭包来设置变量? VAR1 返回 2,但我希望它返回单元格 I2 中的值。

def f_getdata = {ColDesc, ColNum -> 
ColDesc = Float.parseFloat(sheet.getRow(1).getCell(ColNum).getRawValue())}

def VAR1 = 2

f_getdata(VAR1, 8)

【问题讨论】:

  • 参数按值传递,而不是按引用传递。
  • 我想要完成的事情在 Groovy 中是不可能的,或者有解决方法?
  • 我不是 Groovy 专家,但你为什么不简单地使用一个方法,然后从那个方法返回:def var1 = getData(8);
  • 真正的闭包比我发布的更复杂:def f_noNullfld_Getdata_TaxCheck = {ColDesc, ColNum, TaxCompare -> if (f_isNULL(ColNum)) {MarkError(j,err1)} else {ColDesc = Float.parseFloat(myrow.getCell(ColNum).getRawValue()) if (ColDesc > TaxCompare) {MarkError(ColNum,err2)}}} 我只是不想为 excel 文件中的每一列重复相同的代码块。我认为关闭会对此有所帮助。我似乎不喜欢在其中设置一个变量..

标签: java groovy reference closures


【解决方案1】:

大多数类似简单的类型(String、Integer、Long 等)都是不可更改的。

所以你不能做你所描述的。

但如果 VAL1 将在容器中 - 例如 Map - 那么您可以更改地图中的值:

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

println ctx.VAL1

结果:

hello world

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 2014-04-06
    • 2012-10-15
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多