带有 optional 参数的 Groovy 闭包

标签 groovy parameters arguments closures optional

我想定义一个接受一个参数的闭包(我用 it 指代)
有时我想向闭包传递另一个额外的参数。
我怎样才能做到这一点?

最佳答案

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

另一种选择是制作 b像这样的可变参数列表:
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

关于带有 optional 参数的 Groovy 闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12580262/

相关文章:

jenkins - 使用 init.groovy.d 脚本中的管道初始化 Jenkins 2.0

c# - SQL SET 语句 C# 参数

c# - 确定方法接受的参数数量

c - 函数中的 isdigit()

python - 将数组从 bash 传递到 python 参数

java - @sign 有什么作用?

grails - (默认程序包)在GGTS中

groovy - Jenkins 插件安装

Java:设置预定长度的数组作为方法参数?

r - 关于 R 中函数参数的困惑