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

查看:97
本文介绍了使用'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天全站免登陆