Groovy Closure with optional arguments

Moonlit picture Moonlit · Sep 25, 2012 · Viewed 11.8k times · Source

I want to define a closure which takes one argument (which i refer to with it ) sometimes i want to pass another additional argument to the closure. how can i do this?

Answer

tim_yates picture tim_yates · Sep 25, 2012

You could set the second argument to a default value (such as null):

def cl = { a, b=null ->
  if( b != null ) {
    print "Passed $b then "
  }
  println "Called with $a"
}

cl( 'Tim' )          // prints 'Called with Tim'
cl( 'Tim', 'Yates' ) // prints 'Passed Yates then Called with Tim

Another option would be to make b a vararg List like so:

def cl = { a, ...b ->
  if( b ) {
    print "Passed $b then "
  }
  println "Called with $a"
}

cl( 'Tim' )                    // prints 'Called with Tim'
cl( 'Tim', 'Yates' )           // prints 'Passed [Yates] then Called with Tim
cl( 'Tim', 'Yates', 'Groovy' ) // prints 'Passed [Yates, Groovy] then Called with Tim