Groovy中的闭包
我是Groovy的新手。我执行以下Groovy代码:Groovy中的闭包,groovy,Groovy,我是Groovy的新手。我执行以下Groovy代码: myList=[234, 34, "Stackoverflow", 3.14] myList=myList.collect {if (it instanceof Integer) it*it} println myList 它输出: [54756, 1156, null, null] 在我看来,它不应该改变字符串的值。当我将第二行更改为: myList=myList.collect {if (it instanceof In
myList=[234, 34, "Stackoverflow", 3.14]
myList=myList.collect {if (it instanceof Integer) it*it}
println myList
它输出:
[54756, 1156, null, null]
在我看来,它不应该改变字符串的值。当我将第二行更改为:
myList=myList.collect {if (it instanceof Integer) it*it else it=it}
正如我所料:
[54756, 1156, Stackoverflow, 3.14]
我想知道这背后的逻辑是什么 由于您的第一个版本中没有
else
子句,因此结果是null
第二个版本也应该是这样工作的:
myList.collect {if (it instanceof Integer) it * it else it}
由于第一个版本中没有
else
子句,因此结果是null
第二个版本也应该是这样工作的:
myList.collect {if (it instanceof Integer) it * it else it}
我猜原因是,如果元素不是整数并且默认为null,那么您没有指定第一个闭包的结果
println a()
def a() {
if (1==2) "Hello!"
}
>> null
我猜原因是,如果元素不是整数并且默认为null,那么您没有指定第一个闭包的结果
println a()
def a() {
if (1==2) "Hello!"
}
>> null