Groovy Closure with optional arguments

后端 未结 1 967
半阙折子戏
半阙折子戏 2021-02-12 06:00

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 th

相关标签:
1条回答
  • 2021-02-12 06:52

    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
    
    0 讨论(0)
提交回复
热议问题