【问题标题】:Groovy each method returning incorrect resultsGroovy 每个方法返回不正确的结果
【发布时间】:2014-08-01 18:13:49
【问题描述】:

在一些 Groovy 代码中,我写了这行代码

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

解析格式为版本号 XX.XX.XX.XX 的字符串,并将生成的字符串列表转换为整数列表。但是,Groovy 将 intCurrentArray 推断为字符串列表,从而导致不正确的转换。当我将行更改为:

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

转换工作得很好。为什么每种方法都会给出时髦的结果? Groovy 不会查看闭包内部来帮助推断 intCurrentArray 的类型吗?

【问题讨论】:

    标签: java types groovy closures inference


    【解决方案1】:

    each 返回它迭代的相同列表。使用 collect 代替作为参数传递的闭包的每个结果构建一个新列表:

    def intCurrentArray = "99.88.77.66".tokenize('.').collect { it.toInteger() }
    
    assert intCurrentArray == [99, 88, 77, 66]
    

    或扩展运算符:

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

    【讨论】:

    • 所以为了澄清,每个都必须返回一个与您作为参数传递的相同类型的列表?您不是说每个都返回列表不变吗?这对我来说没有意义。
    • 是的。 each 确实返回了调用它的同一个列表,没有改变。你想要的是collect 在每个元素上应用你的闭包的结果。
    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2012-04-11
    • 2016-02-06
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多