简体   繁体   English

在Groovy中关闭

[英]Closure in Groovy

I am new to Groovy. 我是Groovy的新手。 I execute the following Groovy code: 我执行以下Groovy代码:

myList=[234, 34, "Stackoverflow", 3.14]

myList=myList.collect {if (it instanceof Integer) it*it}     

println myList

it outputs: 它输出:

[54756, 1156, null, null]

It seems to me that it shouldn't change the strings value. 在我看来,它不应该改变字符串值。 when I change the second line to: 当我将第二行更改为:

myList=myList.collect {if (it instanceof Integer) it*it else it=it}

it works as I expected: 它像我预期的那样工作:

[54756, 1156, Stackoverflow, 3.14]

I am wondering what is the logic behind that! 我想知道背后的逻辑是什么!

Since there is no else clause in your first version, null is the result. 由于您的第一个版本中没有else子句,因此结果为null

The second version should work like this, too: 第二个版本也应该这样工作:

myList.collect {if (it instanceof Integer) it * it else it}

I guess that the reason is because you have not specified the outcome of the first closure in case an element is not an Integer and it defaulted to null 我想原因是因为你没有指定第一个闭包的结果,以防一个元素不是一个整数并且它默认为null

​println a()

def a() {
   if (1==2) "Hello!"
}​

>> null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM