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()