使用“it"的 Groovy 嵌套闭包 [英] Groovy nested closures with using 'it'

查看:19
本文介绍了使用“it"的 Groovy 嵌套闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

闭包内的代码可以引用it变量.

Code inside closures can refer to it variable.

8.times { println it }

def mywith(Closure closure) {
   closure()
}

mywith { println it }

考虑到这种行为,您不能期望以下代码打印 0011

With this behavior in mind you can't expect following code to print 0011

2.times {
   println it 

   mywith {
      println it
   }
}

相反,我必须写

2.times { i ->
   println i 

   mywith {
      println i
   }
}

我的问题是:为什么没有参数的闭包覆盖 it 变量,即使它们不需要它.

My question is: why closures without parameters override it variable even if they don't need it.

推荐答案

我认为这与 Groovy 的正式闭包定义:

闭包可能有 1...N 个参数,这可能是静态类型的或无类型.第一个参数是可通过隐式无类型如果没有明确的参数命名它参数被命名.如果来电者不指定任何参数,第一个参数(并且,通过扩展,它)将为空.

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.

这意味着 Groovy 闭包将始终至少有一个参数,称为 it(如果没有另外指定)并且 it 如果不作为参数给出,则为 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.

这篇关于使用“it"的 Groovy 嵌套闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆