Why am I getting a “No signature of method”" error when running the closure recursion example in the Groovy shell?

与世无争的帅哥 提交于 2019-12-07 08:32:28

问题


I'm trying to experiment with the Groovy closure recursion example from http://groovy.codehaus.org/JN2515-Closures .

I saved the snippet in a file called recursionTest.groovy and loaded it in the shell, but I'm getting a "No signature of method error":

// recursionTest.groovy   

def results = [];
{ a, b ->
  results << a
  a<10 && call(b, a+b)
}(1,1)

assert results == [1, 1, 2, 3, 5, 8, 13]


groovy:000> load recursionTest.groovy
===> []
ERROR groovy.lang.MissingMethodException:
No signature of method: java.lang.Boolean.call() is applicable for argument types: (groovysh_evaluate$_run_closure1) values: [groovysh_evaluate$_run_closure1@6b7599cc]
Possible solutions: wait(), any(), wait(long), and(java.lang.Boolean), each(groovy.lang.Closure), any(groovy.lang.Closure)
        at groovysh_evaluate.run (groovysh_evaluate:1)
        ...
groovy:003> 

What's going on?


回答1:


I think there are two problems in your script :

  1. In a shell environment you have a certain scope. The variables that are bound are in the "binding". To get one in the binding you must see to it that it's NOT DEFINED before you use it! So no def results. That's not the error that is cast however.

  2. The error that is cast can be fixed by naming your closure recursion. That combined with not defining the results yields :

-

results = []; 

f = { a, b ->   
results << a   
a<10 && call(b, a+b) }(1,1)

assert results == [1, 1, 2, 3, 5, 8, 13]



回答2:


I don't have a perfect answer for you, but it looks like GroovySH has some hacks that can screw it up when working with certain Groovy features.

The example code you have works perfectly in groovyConsole (which is a graphical editor, and much easier to play around in), as well as running it using groovy recursionTest.groovy.

I haven't found a solution that works correctly in the groovy shell, but I wouldn't really recommend using that for learning, anyway.



来源:https://stackoverflow.com/questions/7101550/why-am-i-getting-a-no-signature-of-method-error-when-running-the-closure-recu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!