2017-10-06 3 views
0

Code Groovy: comment passer et retourner des arguments ou des valeursComment partager des arguments (passer et retourner dans les deux sens) entre la fermeture et la méthode comme indiqué ci-dessous code groovy?

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" 
} 

Comment obtenir un accès sur les étiquettes dans le code groovy ci-dessus indiqué.

Je ne sais pas comment utiliser certaines touches comme .call()return à l'intérieur de cette fermeture.

Mise à jour 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" 
} 

sortie réelle:

null 
got 

Résultats escomptés:

5 
got 

Comment résoudre ce ?

Répondre

1

Que diriez-vous quelque chose comme

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" 
}