Groovy嵌套关闭使用’it’

封闭内的代码可以引用它变量.

8.times { println it }

要么

def mywith(Closure closure) {
   closure()
}

mywith { println it }

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

2.times {
   println it 

   mywith {
      println it
   }
}

而是我必须写

2.times { i ->
   println i 

   mywith {
      println i
   }
}

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

解决方法

我认为这与Groovy的 formal Closure definition有关:

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 Closure将始终至少有一个参数,称为它(如果没有指定),如果没有给出参数,它将为null.

第二个例子代替了封闭封闭的范围.

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...