binding - 通过委托(delegate)绑定(bind)时,Groovy 闭包短格式方法调用不起作用?

标签 binding groovy

我创建了一个代码示例,显示了我遇到的问题:

class BindingExample {

    public static void main(String[] args) {

        Closure closure1 = {
            printit.call("Hello from closure 1")
        }

        Closure closure2 = {
            printit("Hello from closure 2")
        }

        Closure printit = { s ->
            println("printing: "+s)
        }

        Binding binding = new Binding()
        binding.setVariable("printit", printit)

        closure1.delegate = binding
        closure2.delegate = binding

        closure1()  //This works fine
        closure2()  //This does not.  

        //Why does .call() work and () alone not?  Most documentation says they're the same.
    }

}

Printit 是 Closure ,其中documentation表示实现了 doCall,因此可以通过 () 以简写形式调用。

但是,当此闭包通过绑定(bind)到委托(delegate)而可用时,仅允许调用的长格式版本。输出是:
printing: Hello from closure 1
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: groovy.lang.Binding.printit() is applicable for argument types: (java.lang.String) values: [Hello from closure 2]

有人可以解释为什么会这样吗?如果可能的话,我还想看看如何制作它,以便简短版本的工作。我能够通过定义 printit 使其工作作为一个适当的静态方法(不是闭包),但这不适用于我的情况,因为我实际上需要为 printit 提供一些仅在方法范围内可用的数据(不包括在示例中,因为我的问题与绑定(bind)有关本身)。

最佳答案

至于为什么会这样,很遗憾,我无法给出明确的答案。有一些关于隐式-“this”注释等的讨论。它似乎应该工作,但是对于应该首先尝试什么(this-scope或delegate)有些模糊。
目前存在的问题似乎是正确的。我发现了以下其他同意的资源,并进行了一些讨论,但没有解决原因。
关于这个问题的 Nabble 讨论:
http://groovy.329449.n5.nabble.com/Binding-Closure-property-not-called-as-method-td5562137.html
JIRA票证结果:
https://issues.apache.org/jira/browse/GROOVY-5367

关于binding - 通过委托(delegate)绑定(bind)时,Groovy 闭包短格式方法调用不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366385/

相关文章:

在 ProcessResources 和过滤器中循环 Gradle

c# - 我希望绑定(bind)到 WPF 列表中的列表

mysql - Ruby 中错误数量的绑定(bind)变量复杂化

binding - 早期绑定(bind)和后期绑定(bind)有什么区别?

c# - 我的 WPF 自定义控件 Datacontext 正在取代父控件

grails - 如果包含GORM查询,如何在Grails中将字符串转换为一段代码?

sorting - Groovy自定义排序

wpf - 一个 View 可以有两个 View 模型作为它的数据上下文吗?

java - jquery+grails,如何将输入数据从对话框传递到 Controller

templates - 这个 Play 模板代码可以简化吗(避免 if/else 标签)?