如何重复Groovy闭包咖喱?

时间:2013-03-29 16:22:53

标签: groovy closures

我正在为Cucumber-JVM实现Groovy步骤定义,我想要一个能够存储自己的步骤,以便下一步可以重复n次。

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

上述代码中“self”应该是什么?

我不能使用“this”,因为它指的是封闭对象(在这种情况下,可能是脚本)。

2 个答案:

答案 0 :(得分:1)

由于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

答案 1 :(得分:0)

您可以尝试使用未引用的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()
}
相关问题