Groovy nested closures with using 'it'

前端 未结 2 1610
南方客
南方客 2021-01-01 14:14

Code inside closures can refer to it variable.

8.times { println it }

or

def mywith(Closure closure) {
   clo         


        
相关标签:
2条回答
  • 2021-01-01 14:49

    If you define a closure like this

    def closure = {println "i am a closure"}
    

    It appears to have no parameters, but actually it has one implicit parameter named it. This is confirmed by:

    def closure = {println "i am a closure with arg $it"}
    closure("foo")
    

    which prints

    "i am a closure with arg foo"

    If you really want to define a closure that takes 0 parameters, use this:

    def closure = {-> println "i am a closure"}
    

    Your example could therefore be rewritten as:

    2.times {
       println it 
    
       mywith {->
          println it
       }
    }
    
    0 讨论(0)
  • 2021-01-01 15:09

    I think it has something to do with the formal Closure definition of Groovy:

    Closures may have 1...N arguments, which may be statically typed or untyped. The first parameter is available via an implicit untyped argument named it if no explicit arguments are named. If the caller does not specify any arguments, the first parameter (and, by extension, it) will be null.

    That means that a Groovy Closure will always have at least one argument, called it (if not specified otherwise) and it will be null if not given as a parameter.

    The second example uses the scope of the enclosing closure instead.

    0 讨论(0)
提交回复
热议问题