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

后端 未结 3 1204
野性不改
野性不改 2021-02-20 11:39

Given following groovy function:

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

The method call would be:

foo([\'a\', \'b         


        
相关标签:
3条回答
  • 2021-02-20 12:21

    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" }
    
    0 讨论(0)
  • 2021-02-20 12:21

    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..

    0 讨论(0)
  • 2021-02-20 12:31

    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.

    0 讨论(0)
提交回复
热议问题