简体   繁体   中英

Closure in Groovy

I am new to Groovy. I execute the following Groovy code:

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.

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

​println a()

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

>> null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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