Why am I getting a "No signature of method"" error when running the closure recursion example in the Groovy shell?
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@6b75开发者_如何学Python99cc]
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?
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.
I think there are two problems in your script :
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.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]
精彩评论