簡體   English   中英

Groovy閉包自身如何進行重復?

[英]How can a Groovy closure curry itself for repetition?

我正在為Cucumber-JVM實現Groovy步驟定義,並且我希望一個步驟能夠存儲自身,以便下一步可以將其重復n次。

Given(~'the (\\S+) is in the blender') { String thing ->
    // do stuff...
    context.repeatable = self.curry(thing)
}

上面的代碼中“自我”應該是什么?

我不能使用“ this”,因為它指的是封閉的對象(無論在這種情況下是什么,也許是腳本)。

由於curryClosure類的方法,因此直接調用curry應用於閉包(如果命名為:

def context

test = { String thing ->
    context = curry(thing)
    thing.toUpperCase() 
}

test('hello')
println context.call()
test('world')
println context.call()

=>

HELLO
WORLD

或匿名:

def context

['test'].each { String thing ->
    context = curry(thing)
    thing.toUpperCase() 
}

println context.call()

=>

TEST

您可以嘗試使用傳遞接收到的參數的未引用curry方法:

clos = { String text ->
    if (text) {
        println "text=$text"
        a = curry null
        a()
    } else {
        println "done"
    }
}

clos "closure text"

將打印:

text=closure text
done

更新

您也可以使用clone()

closure = {
    def clone = clone()
}

暫無
暫無

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

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