加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy嵌套关闭使用’it’

发布时间:2020-12-14 16:35:55 所属栏目:大数据 来源:网络整理
导读:封闭内的代码可以引用它变量. 8.times { println it } 要么 def mywith(Closure closure) { closure()}mywith { println it } 考虑到这种行为,您不能指望打印0011的以下代码 2.times { println it mywith { println it }} 而是我必须写 2.times { i - printl
封闭内的代码可以引用它变量.

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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读