首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带可选参数的Groovy闭包

带可选参数的Groovy闭包
EN

Stack Overflow用户
提问于 2012-09-25 17:41:14
回答 3查看 12.6K关注 0票数 24

我想定义一个带有一个参数的闭包(我用it引用这个参数),有时我想向闭包传递另一个额外的参数。我该怎么做呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-25 17:54:31

您可以将第二个参数设置为默认值(如null):

代码语言:javascript
运行
复制
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成为一个变量列表,如下所示:

代码语言:javascript
运行
复制
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
票数 42
EN

Stack Overflow用户

发布于 2016-05-19 14:58:06

希望这能帮助

代码语言:javascript
运行
复制
​def clr = {...a ->  
    print "Passed $a then "
    enter code here

}

​clr('Sagar')
clr('Sagar','Rahul')
票数 3
EN

Stack Overflow用户

发布于 2018-04-06 16:25:57

的变体不能与@TypeChecked (在类上下文中)一起工作,至少在Groovy 2.4.11中不能工作,在Groovy 2.4.11中,默认参数被忽略,并且不编译 :-(

因此,在这种情况下可以工作的其他(诚然更丑陋的)解决方案是:

closure first似乎工作得很好(对于递归来说无论如何都是必要的):

  1. declaring first

def cl ={ ... }

代码语言:javascript
运行
复制
- at least in Eclipse Neon / Groovy-Eclipse Plugin 2.9.2 the code completion/suggestions do not work either way using the closure later on in the same code block => so nothing lost as far as I can say

带有@TypeChecked(value=TypeCheckingMode.SKIP)

  1. 它对这两种方法都有效,但是您会放松对方法(或类,取决于您放置它的位置)的类型检查
  2. 声明闭包委托 cl2

@TypeChecked class Foo { static main( String[] args ){ def cl ={ a,b -> if( b != null ) print“传递了$b然后”println“用$a调用”} def cl2 ={a -> cl( a,null )} cl2( 'Tim‘) //打印’用Tim‘cl( 'Tim',' Yates‘) //打印’传递的Yates然后用Tim调用}}

  • 闭包转换为类方法,例如

@TypeChecked class Foo { cl( a,b=null ){ if( b != null ) print“通过$b然后”println“用$a调用”} static main( String[] args ){ cl( ' Tim‘) //用Tim’cl( 'Tim',' Yates‘) //打印’通过Yates然后用Tim调用} }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12580262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档