Groovy makes closures a first-class citizen. Each closure extends the abstract class groovy.lang.Closure<V>
, and in the case of an undefined argument type, you can use instanceof
it to check whether a parameter has been passed to the method is a closure. Something like that:
def closure = {
println "Hello!"
}
def foo(p) {
if (p instanceof Closure) {
p()
}
}
foo(closure)
Running this script generates the output:
Hello!
Using a specific type of parameter
Groovy ( ) . , p
, , . :
def closure = {
println "Hello!"
}
def foo2(Closure cl) {
cl()
}
foo2(closure)
foo2("I'm not a closure")
, ( "Hello!" ), :
Hello!
Caught: groovy.lang.MissingMethodException: No signature of method: test.foo2() is applicable for argument types: (java.lang.String) values: [I'm not a closure]
Possible solutions: foo2(groovy.lang.Closure), foo(java.lang.Object), find(), find(groovy.lang.Closure), wait(), run()
groovy.lang.MissingMethodException: No signature of method: test.foo2() is applicable for argument types: (java.lang.String) values: [I'm not a closure]
Possible solutions: foo2(groovy.lang.Closure), foo(java.lang.Object), find(), find(groovy.lang.Closure), wait(), run()
at test.run(test.groovy:18)
, , , , , .