【问题标题】:Groovy convert from List to var args for method callGroovy 从 List 转换为 var args 以进行方法调用
【发布时间】:2013-01-22 07:20:04
【问题描述】:

我正在使用一个提供电子邮件功能的插件,如下所示:

class SendSesMail {

    //to
    void to(String ... _to) { 
        this.to?.addAll(_to)
        log.debug "Setting 'to' addresses to ${this.to}"
    }

}

文档说明该类的调用如下:

sesMail {
    from "from@a.com"
    replyTo "reply@a.com"
    to "t@a.com", "t@b.com", "t@c.com"
    subject "Subject"
    html "Body HTML"
}

在代码中建立了List 的地址,我试图弄清楚如何将此列表转换为该方法期望的 var args。

转换为与“,”连接的String 无效,因为这是一个无效的电子邮件地址。我需要能够将每个列表项分成一个单独的参数,以避免遍历列表并单独发送每封电子邮件。

【问题讨论】:

  • 上面的代码有错误吗?

标签: list groovy variadic-functions


【解决方案1】:

可能扩展运算符 * 就是您要查找的内容:

def to(String... emails) {
    emails.each { println "Sending email to: $it"}
}

def emails = ["t@a.com", "t@b.com", "t@c.com"]
to(*emails)
// Output: 
// Sending email to: t@a.com
// Sending email to: t@b.com
// Sending email to: t@c.com

请注意,对to 的方法调用上的括号是强制性的,否则to *emails 将被解析为乘法。重载语法符号的错误选择 IMO =P

【讨论】:

  • 我从未见过在这种情况下使用扩展运算符,我无法在一个简单的示例中让它工作 - 你能指出一些其他使用它的例子吗?
  • 问题中的代码是否应该按原样运行(没有展开运算符)?例如:尝试:def a( String... p ) { p.each { println it } } ; a 'a', 'b', 'c'
  • @tim_yates 是的。但我 认为 OP 的意思是该代码 sn-p 来自文档,他想做的是使用来自 List 的参数调用该方法。
  • @SteveD This 是我可以在 Groovy 文档中找到的方法调用中使用的扩展运算符的唯一引用。此答案中的代码应按原样在 Groovy 控制台中运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多