Aditya
Aditya

Reputation: 9

Groovy: How to invoke methods when closure is one of the parameter

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

Answers (1)

tim_yates
tim_yates

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!" }

Edit

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

Related Questions