【问题标题】:Nesting groovy each{} inside find{}在 find{} 中嵌套 groovy each{}
【发布时间】:2015-11-27 10:20:27
【问题描述】:

我知道我们不能像.find{} 闭包那样从常规的.each{} 闭包返回。我仍然很好奇为什么下面的代码只执行.find{} 的第一次迭代。

def findlist = [1,2,3,4,5]  
def eachlist = [7,6,5]

findlist.find
{
    int findelem = it
    println "findelem : " + findelem
    eachlist.each
    {
        int eachelem = it
        println "eachelem : " + eachelem  
        if(it == findelem)
        {
            return true  
        }
        return false
    }   
}

打印出来:

findelem : 1
eachelem : 7
eachelem : 6
eachelem : 5

为什么find{} 在第一次迭代后退出?

PS:我知道这段代码可能没有任何实际意义,只是对常规行为感到好奇。

【问题讨论】:

    标签: groovy


    【解决方案1】:

    因为each 返回未修改 集合正在迭代。返回的集合计算为true,因此find 在第一次迭代后停止。

    看看下面的代码:

    assert [1, 2].each { println it } == [1,2]
    
    assert [1,2].find { println it; [3, 4].each { e -> println e } }
    

    您需要嵌套find 而不是each

    【讨论】:

    • 所以each{} 总是返回它正在迭代的整个集合?
    • 是的,这就是它的工作原理。请查看sources
    【解决方案2】:

    为了完成 Opal 的回答(每个都返回集合,因此如果它不为空,则计算结果为 true),您可以使用 find 闭包内的局部变量来返回 找到的值。稍微简化一下代码:

    assert 5 == findlist.find { findelem ->
        println "findelem : " + findelem
        boolean found
        eachlist.each { eachelem ->
            println "eachelem : " + eachelem  
            found = (eachelem == findelem)
        }
        found
    }
    

    但是,有一个更好更时髦的方法:

    assert 5 == findlist.find { it in eachlist }
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 2012-08-15
      • 2023-03-07
      • 2016-05-04
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多