【问题标题】:Groovy Closure with optional arguments带有可选参数的 Groovy 闭包
【发布时间】:2012-09-16 19:29:04
【问题描述】:

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

【问题讨论】:

    标签: groovy parameters arguments closures optional


    【解决方案1】:

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

    【讨论】:

    • @user1291235 没问题 :-) 添加了另一个可能的解决方案
    • 如果你不想改变闭包体,你可以将第一个参数命名为'it' :-)
    • 至少在 2.4.11 中默认 arg 被忽略并且不能使用 @TypeChecked 编译 :-( - 使用 @TypeChecked(value=TypeCheckingMode.SKIP) 它再次工作......与可变参数版本相同
    【解决方案2】:

    希望这会有所帮助

    ​def clr = {...a ->  
        print "Passed $a then "
        enter code here
    
    }
    
    ​clr('Sagar')
    clr('Sagar','Rahul')
    

    【讨论】:

      【解决方案3】:

      @tim_yates 的变体不适用于 @TypeChecked(在类上下文中),至少对于忽略默认参数的 Groovy 2.4.11无法编译 :-(

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

      1. 首先声明闭包似乎工作正常(无论如何都是递归所必需的):

        def cl
        cl = { ... }
        
        • 至少在 Eclipse Neon / Groovy-Eclipse Plugin 2.9.2 中,代码完成/建议在以后在同一代码块中使用闭包时都不起作用 => 所以据我所知没有任何损失
      2. 使用 @TypeChecked(value=TypeCheckingMode.SKIP) 对两者都适用,但随后您将放松对方法(或类,取决于您放置它的位置)的类型检查

      3. 声明闭包委托cl2

        @TypeChecked
        class Foo { 
        
          static main( String[] args ) {
        
            def cl = { a, b ->
              if( b != null )
                print "Passed $b then "
              println "Called with $a"
            }
            def cl2 = { a -> cl( a, null ) }
        
            cl2( 'Tim' )         // prints 'Called with Tim'
            cl( 'Tim', 'Yates' ) // prints 'Passed Yates then Called with Tim           
          }
        }
        
      4. 闭包转化为类方法,例如

        @TypeChecked
        class Foo { 
        
          cl( a, b=null ) {
            if( b != null )
              print "Passed $b then "
            println "Called with $a"
          }
        
          static main( String[] args ) {
            cl( 'Tim' )          // prints 'Called with Tim'
            cl( 'Tim', 'Yates' ) // prints 'Passed Yates then Called with Tim           
          }
        }
        

      【讨论】:

        猜你喜欢
        • 2011-08-06
        • 2013-08-11
        • 2013-05-26
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 2016-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多