closureinclosurebug.groovy

来自「Groovy动态语言 运行在JVM中的动态语言 可以方便的处理业务逻辑变化大的业」· GROOVY 代码 · 共 31 行

GROOVY
31
字号
/**
 * Bug illustrating the nested closures variable scope visibility issue.
 * l.each is ClosureInClosureBug$1 and it.each is ClosureInClosureBug$2
 * The variable text is not visible from ClosureInClosureBug$2.
 * Indeed, a closure can only see the variable defined outside this closure (one level up)
 * but cannot see what's in the second level.
 *
 * In order to make the test work, do not forget to uncomment the line "println(text)"
 *
 * @authour Guillaume Laforge
 */
class ClosureInClosureBug extends GroovyTestCase {

    void testInvisibleVariable() {
        def text = "test "

        def l = [1..11, 2..12, 3..13, 4..14]

        l.each {
            //println(text)
            it.each{
                println(text)
            }
        }
    }

    static void main(args) {
        def bug = new ClosureInClosureBug()
        bug.testInvisibleVariable()
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?