gpt4 book ai didi

Groovy 全局闭包在嵌套方法调用中不起作用

转载 作者:行者123 更新时间:2023-12-02 21:54:13 25 4
gpt4 key购买 nike

我有一个简单的闭包,我希望能够在我的代码中使用它来测量任何其他闭包所需的时间。它看起来像这样:

def benchmark = {name,closure ->
start = System.currentTimeMillis()
ret = closure.call()
now = System.currentTimeMillis() println(name + " took: " + (now - start))
ret
}

当从同一范围调用时它会起作用,如下所示:

benchmark('works') { println("Hello, World\n")}

但是当它调用嵌套作用域时它似乎不起作用

def nested()
{
benchmark('doesnt_work'){print("hello")}
}

nested()

最佳答案

那是因为您在脚本中运行它。

Groovy 将以上内容转换为:

class Script {
def run() {
def benchmark = {name,closure -> ...
nested()
}

def nested() {
benchmark('doesnt_work'){print("hello")}
}
}

如您所见,闭包对于隐式 run 方法是本地的,但 nested 方法属于该类...

我相信你有3个选择:

  1. nested设为闭包,它们将存在于同一范围内

    def benchmark = {name,closure ->
    start = System.currentTimeMillis()
    ret = closure.call()
    now = System.currentTimeMillis()
    println(name + " took: " + (now - start))
    ret
    }

    def nested = {
    benchmark('doesnt_work'){print("hello")}
    }

    nested()
  2. 编写适当的类并自己控制范围

    class Test {
    def benchmark = {name,closure ->
    long start = System.currentTimeMillis()
    def ret = closure.call()
    long now = System.currentTimeMillis()
    println(name + " took: " + (now - start))
    ret
    }

    def nested() {
    benchmark('doesnt_work'){print("hello")}
    }

    static main( args ) {
    new Test().nested()
    }
    }
  3. def benchmark = {name,closure -> ... 之前添加 @groovy.transform.Field 这会将闭包定义提升为property of this Script class

    @groovy.transform.Field def benchmark = { name, closure ->
    start = System.currentTimeMillis()
    ret = closure.call()
    now = System.currentTimeMillis()
    println(name + " took: " + (now - start))
    ret
    }

    def nested() {
    benchmark('doesnt_work'){print("hello")}
    }

    nested()

关于Groovy 全局闭包在嵌套方法调用中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com