簡體   English   中英

從Groovy中的閉包返回方法

[英]Returning a method from closure in groovy

由於閉包的行為類似於內聯方法(我猜想,閉包在技術上被編譯為類),所以我沒有找到如何從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 :('
}

我不熟悉groovy,但這似乎是預期的行為。 通常,在每個語句中,它實際上是針對數組中的每個值單獨運行一個函數。

因此,您在值首次為1時運行它,它傳遞了if語句,然后返回。

然后運行下一個函數,這次的值為2。 它輸出2,該值不通過if語句,然后返回,因為它是函數的結尾。

如果只想打印與之匹配的值,則可以這樣做。

public static returnFromClosure()
    {
        [1,2,3].each{

        if (it == 1)
            println it          
    }
}

如果要停止執行每個函數,並在找到等於一個的值后繼續操作,則應查看另一篇文章。 是否有可能打破常規

根據您的更新進行編輯:

我沒有一種特定的機制可以像您所說的那樣起作用。 閉包只是在特定上下文中編寫的函數,就像其他函數僅從其自身的執行返回一樣。 我想您想要的是這樣的東西。

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 :('
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM