2013-01-22 30 views
21

我使用一个插件,提供电子邮件功能如下:Groovy中从列表转换为变参的方法调用

class SendSesMail { 

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

} 

文档状态的类被称为如下:

sesMail { 
    from "[email protected]" 
    replyTo "[email protected]" 
    to "[email protected]", "[email protected]", "[email protected]" 
    subject "Subject" 
    html "Body HTML" 
} 

在代码List的地址是建立起来的,我想弄清楚如何将这个列表转换为该方法所期望的var args。

转换为String与“,”连接不起作用,因为这是一个无效的电子邮件地址。我需要能够将每个List项目分离为一个单独的参数,以避免迭代List并单独发送每封电子邮件。

+0

您是否收到上述代码的错误? –

回答

43

可能蔓延运营商,*,是你在找什么:

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

def emails = ["[email protected]", "[email protected]", "[email protected]"] 
to(*emails) 
// Output: 
// Sending email to: [email protected] 
// Sending email to: [email protected] 
// Sending email to: [email protected] 

注意在方法调用的括号to是强制性的,否则将to *emails被解析为一个乘法。语法符号超负荷的错误选择IMO = P

+0

我从来没有见过在这种情况下使用传播运算符,我不能让它在一个简单的例子中工作 - 你能指出一些使用它的其他例子吗? – SteveD

+0

问题中的代码不应该像原来那样运行(没有扩展运算符)?例如:try:'def a(String ... p){p.each {println it}}; a','b','c'' –

+0

@tim_yates是的。但我认为OP意味着该代码片段来自文档,他想要做的是使用来自List的参数调用该方法。 – epidemian