12

Closure を引数として受け取り、それに 2 つの引数を渡すメソッドを書きたいのですが、そのクロージャを書く人は、好きなように 1 つまたは 2 つの引数を指定できます。

私はこのようにしてみました:

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

このコードを実行しようとすると、結果は次のようになります。

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)

どうすればいいですか?

4

2 に答える 2

31

maximumNumberOfParametersClosure を呼び出す前に、その Closure を要求できます。

def method(Closure c){
    def firstValue = 'a'
    def secondValue = 'b'
    if (c.maximumNumberOfParameters == 1)
        c(firstValue)
    else
        c(firstValue, secondValue)
}

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

出力:

I just need a
I need both a and b
于 2012-08-22T17:16:37.637 に答える
3

最も簡単な方法は、デフォルト値を与えることです:

method { a, b=nil ->
   println "I just need $a"
}

配列を使用することもできます:

method { Object[] a ->
  println "I just need $a"
}
于 2012-08-22T16:39:00.327 に答える