Groovy: how to pass varargs and close the method at the same time?

Given the following groovy function:

def foo(List<String> params, Closure c) {...} 

Method call:

 foo(['a', 'b', 'c']) { print "bar" } 

But I would like to get rid of the brackets (List) in the function call. sort of:

 foo('a', 'b') { print "bar" } 

I cannot change the list parameter to varargs, because varargs can only be the last parameter in the function (here closing is the last).

Any suggestion?

+6
source share
3 answers

Seeing that it is impossible to achieve exactly what you want (it is written in the Groovy documentation that your particular case is a problem, unfortunately, they transfer documents, so I cannot directly link them directly), that these lines are about something:

 def foo(String... params) { println params return { Closure c -> c.call() } } foo('a', 'b') ({ println 'woot' }) 

Now you need to put the closure in brackets, but you no longer need to use an array.

+8
source

I think this is only possible if you use an array as an argument or a variable length argument list :

 def foo(Object... params) { def closureParam = params.last() closureParam() } foo('a', 'b') { print "bar" } 
+4
source

There is always a bad person Varargs ™

 def foo(String p1, Closure c) {foo [p1], c} def foo(String p1, String p2, Closure c) {foo [p1, p2], c} def foo(String p1, String p2, String p3, Closure c) {foo [p1, p2, p3], c} def foo(String p1, String p2, String p3, String p4, Closure c) {foo [p1, p2, p3, p4], c} ... 

I'm only half joking.

+3
source

Source: https://habr.com/ru/post/979409/


All Articles