Groovy code: how to pass and return arguments or values
def method (int a, Closure c) {
Query q = new Query()
c.delegate = q
c()
//label 1: pass a to label 2 and get str from there
}
class Query
{
void key (String str) {
//label 2: return str and get a to method label 1.
}
}
method(5) {
key "got"
}
How to get access on both labels in above shown groovy code.
I don't know how to use some keys like .call()
return
inside this closure.
Update 1:
def method (int a, Closure c) {
Query q = new Query()
c.delegate = q
c.call(a)
def str = q.str
println str
}
class Query
{
def str
def a
void key (String str) {
this.str = str
this.a=a
println a
}
}
method(5) {
key "got"
}
Actual Output:
null
got
Expected Output:
5
got
How to solve this ?
How about something like
def method (int a, Closure c) {
Query q = new Query()
q.a = a
c.delegate = q
c.call()
def str = q.str
println str
}
class Query
{
def str
def a
void key (String str) {
this.str = str
println a
}
}
method(5) {
key "got"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.