Reputation: 1
Below is the Jenkins groovy code in scripted pipeline, we use to pass methods
def dict = [:]
def register(String x, Closure y){ dict[x]=y }
we say register('a', this.&foo)
to pass a method to register()
accepting closures as second argument
where foo()
is a method
def foo(parm){
// do something with parm
}
where parm
's possible value is 'a'
What should be the type of second argument of register
method to avoid passing this.&foo
and rather invoke register('a', foo)
?
Upvotes: 0
Views: 3123
Reputation: 636
Function reference can be obtained using the "&" character; e.q this.&bar
def foo(Closure c) {
c("foo")
}
def bar(arg) {
println "Hellow World: ${arg}"
}
println(foo(this.&bar))
Output:
Hellow World: foo
Upvotes: 0
Reputation: 42272
If you want to invoke register('a', foo)
then foo
has to be a closure like e.g.
def foo = {
// closure body here
}
instead of
def foo() {
// method body here
}
The construction this.&foo
is called method pointer operator and it is used to transform a method to a closure. If foo
has to remain a method then you can't avoid this.&foo
operator. Groovy does not support passing methods as foo
. On the other hand, your register
method expects a closure as a second parameter, so have to options:
foo
as a closurefoo
method to a closure with this.&foo
operatorUpvotes: 2