【问题标题】:Returning a method from closure in groovy从groovy中的闭包中返回一个方法
【发布时间】:2015-08-07 14:06:14
【问题描述】:

由于闭包的行为类似于内联方法(我猜,从技术上讲,闭包被编译为类),我没有找到如何在 Groovy 中从闭包返回方法。

例如,如果我没有使用闭包,从main() 调用下面的方法应该只打印 1,但使用闭包它会打印所有 1、2、3:

public static returnFromClosure()
{
    [1,2,3].each{
        println it
        if (it == 1)
            return            
    }
}

我怎样才能实现这种行为?

编辑

问题已作为重复问题关闭。 我的问题是关于一般的关闭。我举了each{} 循环的例子,它涉及到闭包。我知道关于在each{} 循环中使用breakcontinue 的问题存在,但这将涉及中断该循环或继续循环的下一次迭代,而不是返回调用代码。这种误解背后的罪魁祸首似乎是我上面给出的例子。然而,在任何循环中使用return 与使用break 不同。我最好给出不同的例子。在这里,简单的关闭:

static main(def args)
{
    def closure1 = { 
                      println 'hello';
                      return; //this only returns this closure, 
                              //not the calling function, 
                              //I was thinking if I can make it 
                              //to exit the program itself
                      println 'this wont print' 
                   }
    closure1();
    println 'this will also print :('
}

【问题讨论】:

    标签: design-patterns groovy closures


    【解决方案1】:

    我不熟悉 groovy,但这似乎是预期的行为。通常在每个语句中,它实际上是分别为数组中的每个 值运行一个函数。

    所以你第一次运行它的值是一个,它通过 if 语句然后返回。

    然后下一个函数运行,这次的值为 2。它打印出 2,该值没有通过 if 语句然后返回,因为它是函数的结尾。

    如果您只想打印匹配的值,您可以这样做。

    public static returnFromClosure()
        {
            [1,2,3].each{
    
            if (it == 1)
                println it          
        }
    }
    

    如果您想停止执行每个函数并在找到一个等于 1 的值后继续执行,您应该查看这篇文章。 is it possible to break out of closure in groovy

    根据您的更新进行编辑:

    据我所知,没有像您所说的那样有效的特定机制。闭包只是在特定上下文中编写的函数,就像任何其他函数一样,仅从它们自己的执行中返回。我想你想要的是这样的。

    static main(def args){
        done = false;
    
        def closure1 = { 
                          println 'hello';
                          done = true;
                          return; //this only returns this closure, 
                                  //not the calling function, 
                                  //I was thinking if I can make it 
                                  //to exit the program itself
                          println 'this wont print' 
                       }
        closure1();
    
        if( done ){
            return;
        }
    
        // this will no longer print =)
        println 'this will also print :('
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2010-10-20
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多