当通过委托绑定时,Groovy闭包短格式方法调用不起作用?

问题描述:

我创建一个代码示例,示出了我遇到的问题:当通过委托绑定时,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,因此在短形式可调用经由()。

但是,如果通过绑定到委托可以实现此闭包,则只允许调用的长格式版本。输出是:

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在方法范围内提供一些可用的数据(不包括在这个例子中,因为我的问题涉及绑定本身)。

+0

我猜这是任何一个错误或在Groovy计划失败。它必须尝试“this.printit()”,而不是检查名为“printit”的闭包的本地和委托空间。尝试这个?在closure2中将其更改为(printit)()并查看是否有效。 – billjamesdev 2013-03-12 17:57:24

至于为什么这是这种情况,不幸的是我不能给出明确的答案。有一些关于隐含 - “这个”注释的讨论等等。它似乎应该起作用,但是应该先尝试什么(这个范围或委托)有一些模糊性。

目前存在的问题似乎是正确的。我发现以下其他资源是一致的,有些讨论没有解决原因。关于这个问题

Nabble讨论: http://groovy.329449.n5.nabble.com/Binding-Closure-property-not-called-as-method-td5562137.html

JIRA票造成: ​​