groovy méthode qui prennent fermeture avec un ou deux arguments

Je voudrais écrire une méthode qui prennent une Fermeture comme argument et passer de remorquage arguments, mais qui écrivent que la clôture pouvez spécifier un ou deux arguments qu'il préfère

J'ai essayé de cette façon:

def method(Closure c){
     def firstValue = 'a'
     def secondValue = 'b'
     c(firstValue, secondValue);
}

//execute
method { a ->
   println "I just need $a"
}
method { a, b ->
   println "I need both $a and $b"
}

Si j'essaie d'exécuter ce code, le résultat est:

Caught: groovy.lang.MissingMethodException: No signature of method: clos2$_run_closure1.call() is applicable for argument types: (java.lang.String, java.lang.String) values: [a, b]
Possible solutions: any(), any(), dump(), dump(), doCall(java.lang.Object), any(groovy.lang.Closure)
    at clos2.method(clos2.groovy:4)
    at clos2.run(clos2.groovy:11)

Comment puis-je le faire?

OriginalL'auteur rascio | 2012-08-22