Groovy convert from List to var args for method call

16,076

Probably the spread operator, *, is what you're looking for:

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]

Notice that the parentheses on the method call to to are mandatory, as otherwise to *emails would be parsed as a multiplication. Bad choice of overloaded grammar symbols IMO =P

Share:
16,076
Conor Power
Author by

Conor Power

Updated on June 05, 2022

Comments

  • Conor Power
    Conor Power almost 2 years

    I am using a plugin that provides email functionality as follows:

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

    The documentation states the class is called as follows:

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

    In the code a List of addresses is built up and I'm trying to figure out how to convert this list to the var args expected by the method.

    Converting to a String concatenated with "," doesn't work as this is an invalid email address. I need to be able to separate each List item into a separate parameter to avoid having to iterate over the List and send each email individually.