在内部闭包调用中设置外部闭包值

时间:2016-03-16 15:01:22

标签: groovy

我有这样的设施

class Core {

    def call(Closure c) {
        c.delegate = this
        c()
        this
    }

    def slide = { title, closure ->
        def slideWriter = new SlideWriter()
        closure.delegate = slideWriter
        closure()
        slideWriter
    }

    private class SlideWriter {

        def text = { position, closure ->
            def value
            closure.delegate = text
            closure()
            println "Value: " + value // null
        }
    }
}

def c = new Core()

c {
    slide ("title") {
        text(1) {
            value = "Some text"
        }
    }
}

我想要的是使用闭包设置def value的值,传递给text invokation。

但它显示Value: null。 为什么这样以及如何正确设置value

1 个答案:

答案 0 :(得分:1)

我不相信你可以。

但是,您可以将幻灯片更改为此

def slide = { title, closure ->
    def slideWriter = new SlideWriter()
    closure.delegate = slideWriter
    closure.resolveStrategy = Closure.DELEGATE_FIRST
    closure()
    slideWriter
}

SlideWriter

private class SlideWriter {
    def value
    def text = { position, closure ->
        closure()
        println "Value: " + value // null
    }
}

它应该可行