简体   繁体   English

Groovy每个方法返回错误的结果

[英]Groovy each method returning incorrect results

In a bit of Groovy code I had written the line 用一些Groovy代码编写了这一行

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. 它解析格式为版本号XX.XX.XX.XX的字符串,并将结果字符串列表转换为整数列表。 However, Groovy inferred intCurrentArray to be a list of strings instead, causing an incorrect conversion. 但是,Groovy推断intCurrentArray而是一个字符串列表,从而导致错误的转换。 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? Groovy不会在闭包内部查找以帮助推断intCurrentArray的类型吗?

each returns the same list it iterated. each返回迭代的相同列表。 Use collect instead to build a new list from each result of the closure passed as argument: 使用collect代替根据作为参数传递的闭包的每个结果构建一个新列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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