groovy: how to pass varargs and closure in same time to a method?

我是研究僧i 提交于 2019-12-10 02:54:37

问题


Given following groovy function:

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

The method call would be:

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

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

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

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

Any suggestion?


回答1:


Seeing that it's impossible to achieve exactly what you want (it's written in Groovy documentation that your specific case is a problem, unfortunately they are migrating the docs so I can't directly link right now), what about something along these lines:

def foo(String... params) {
    println params
    return { Closure c ->
        c.call()
    }
}

foo('a', 'b') ({ println 'woot' })

Now you need to put the closure in parantheses, but you don't need to use an array anymore..




回答2:


I think this only could be possible if you use an array as argument or an Variable-Length Argument List :

def foo(Object... params) {
    def closureParam = params.last()
    closureParam()
}

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



回答3:


There's always Poor Man's 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.



来源:https://stackoverflow.com/questions/27406559/groovy-how-to-pass-varargs-and-closure-in-same-time-to-a-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!