带有可选参数的Groovy Closure

Moo*_*lit 22 parameters groovy closures arguments optional

我想定义一个带有一个参数的闭包(我将其引用it)有时我想将另一个参数传递给闭包.我怎样才能做到这一点?

tim*_*tes 37

您可以将第二个参数设置为默认值(例如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
Run Code Online (Sandbox Code Playgroud)

另一种选择是b像这样制作一个vararg List:

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
Run Code Online (Sandbox Code Playgroud)