groovy:如何传递varargs和闭包在同一时间到一个方法? [英] groovy: how to pass varargs and closure in same time to a method?

查看:112
本文介绍了groovy:如何传递varargs和闭包在同一时间到一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下groovy函数:

Given following groovy function:

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

方法调用将是:

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

但我想在函数调用中摆脱括号(List)。例如:

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

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

我不能将列表参数更改为varargs,因为varargs只能是函数中的最后一个参数(这里闭包是最后一个参数)。

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

有任何建议吗?

推荐答案

看到这是不可能实现你想要的(它是写在Groovy文档中,你的具体情况是一个问题,不幸的是他们正在迁移文档,所以我现在不能直接链接),那么沿着这些线:

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' })

现在你需要把闭包放在parantheses中,但是你不需要再使用数组。

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

这篇关于groovy:如何传递varargs和闭包在同一时间到一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆