简体   繁体   中英

Groovy each() method does not iterate properly

I came across a strange behavior of the each() method when trying this code:

def xml = new XmlSlurper().parseText('''
<list>
    <item a="1">a</item>
    <item a="2">b</item>
    <item a="1">c</item>
</list>
''')

def i = 0
xml.'**'.findAll { it.@a=='1' }.each {
    println "hi" + i
}  

The result is only hi0 , however I would expect hi0hi1 . Is this behavior a bug or per language design? The second result is only provided if I write println "hi" + i++ instead of the current closure body, so when the content is different for each item...

Your i variable is not being incremented because there's nothing that tells it to increment. The way your code is currently written, I would expect the output to be:

hi0
hi0

I think what you are looking for is eachWithIndex , which provides the closure with two arguments - the current item and the index of the item. Your code would then look like this:

def xml = new XmlSlurper().parseText('''
<list>
    <item a="1">a</item>
    <item a="2">b</item>
    <item a="1">c</item>
</list>
''')

xml.'**'.findAll { it.@a=='1' }.eachWithIndex { item, i ->
    println "hi" + i
}

This results in an output of:

hi0
hi1

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