简体   繁体   中英

Groovy each method returning incorrect results

In a bit of Groovy code I had written the line

def intCurrentArray = currentVersion.tokenize('.').each({x -> Integer.parseInt(x)})

which parses a string formatted like a version number XX.XX.XX.XX and converts the resulting list of strings to a list of integers. However, Groovy inferred intCurrentArray to be a list of strings instead, causing an incorrect conversion. When I changed the line to:

ArrayList intCurrentArray = []
for (x in currentVersion.tokenize('.'))
   intCurrentArray.add(Integer.parseInt(x))

the conversion worked just fine. Why would the each method give funky results? Does Groovy not look inside the closure to help infer the type of intCurrentArray?

each returns the same list it iterated. Use collect instead to build a new list from each result of the closure passed as argument:

def intCurrentArray = "99.88.77.66".tokenize('.').collect { it.toInteger() }

assert intCurrentArray == [99, 88, 77, 66]

Or the spread operator:

def intCurrentArray = "99.88.77.66".tokenize('.')*.toInteger() 

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