Reputation: 9
This is my closure method and i am looking for different ways to invoke this groovy method
myMethod(Closure c, def val) {
if(c)
c.call()
println val
}
Things i tried:
myMethod({/*code*/},"print something")
Is there a way i can skip braces or a better way to do the same?
Upvotes: 1
Views: 616
Reputation: 171054
Put the Closure last in the definition:
def myMethod(val, Closure c) {
if(c) c.call()
println val
}
Then you can do:
myMethod("print something") { -> println "closure!" }
Think you're going to need 2 methods:
def myMethod(Closure c) {
myMethod('default', c)
}
def myMethod(val, Closure c) {
if(c) c.call()
println val
}
Then you can do:
myMethod('tim') { println 'woo' }
or
myMethod { println 'woo' }
Upvotes: 1