Groovy:更新闭包内的外部变量形式

问题描述 投票:0回答:1

我下面有以下常规代码片段:

import groovy.xml.StreamingMarkupBuilder;

def processData() {
     // xml builder
    def xmlBuilder = new StreamingMarkupBuilder()
    xmlBuilder.encoding = 'UTF-8'
    
    // data
    def body = [1, 2, 3]
    flag = '0'
    
    def idocXML = xmlBuilder.bind {
        ROOT {
            body.each { line ->
                flag = '1'
            }
        }
    }// end of xml builder bind
   
    println("$flag")
}

processData()

在代码片段中,processData 内部有一个变量标志,初始化为 0,在 xmlBuilder.bind 和主体迭代内部,我将标志更新为 1。但是在这些闭包之外,当我打印标志时,它显示为0.

如何将 body.each 闭包内部的标志更新为 1?谢谢

variables groovy closures
1个回答
0
投票

您的代码通常是正确的,并且会执行它应该执行的操作。问题是这个

bind
闭包被声明了,但实际上从未被调用过。您声明了应如何构造 XML,但您从未“触发”构造本身。 让我告诉你我的意思以及我是如何发现它的。我的第一个问题是,这
flag = '1'
行是否已执行?我通过添加额外的输出来更改代码:

body.each { line ->
    println "line = $line" // this is the line I've added.
    flag = '1'
}

如您所见,它什么也没打印。为什么?因为,正如我上面所写,您描述了如何构造

idocXML
对象,但您从未使用过该对象。这就是为什么从未调用此绑定闭包的原因。这是按预期工作的代码:

import groovy.xml.StreamingMarkupBuilder;

def processData() {
    // xml builder
    def xmlBuilder = new StreamingMarkupBuilder()
    xmlBuilder.encoding = 'UTF-8'

    // data
    def body = [1, 2, 3]
    flag = '0'

    def idocXML = xmlBuilder.bind {
        ROOT {
            body.each { line ->
                println "line = $line" // make sure that binding is actually calledd
                flag = '1'
            }
        }
    }// end of xml builder bind

    println idocXML.toString() // do something with the object to actually call binding

    println("$flag") // now, at that point, the flag will have a new value, because the binding logic updated it.
}

processData()

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.