quantoid
quantoid

Reputation: 588

How can a Groovy closure curry itself for repetition?

I'm implementing Groovy step definitions for Cucumber-JVM and I want a step to be able store itself so that the next step can repeat it n times.

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

What should "self" be in the above code?

I can't use "this" as that refers to the enclosing object (whatever that is in this case, maybe the script).

Upvotes: 2

Views: 616

Answers (2)

Will
Will

Reputation: 14529

You can try using unreferenced curry method passing the received parameters:

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

clos "closure text"

Will print:

text=closure text
done

Update

You can also use clone():

closure = {
    def clone = clone()
}

Upvotes: 0

jalopaba
jalopaba

Reputation: 8119

Since curry is a method of the Closure class, directly invoking curry applies to the closure, both if it is named:

def context

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

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

=>

HELLO
WORLD

or anonymous:

def context

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

println context.call()

=>

TEST

Upvotes: 1

Related Questions