Michael Meng
Michael Meng

Reputation: 33

Groovy parameter "String..."

I'm in the midst of implementing unit tests for a web application and I've come across this piece of code (and some others) that have a parameter as "String..." I'm not sure what the "..." means, if anything at all, as I can't find any explanation anywhere.

public static List<User> getUsersForGroups(String... dns) {
    Set<String> members = getMembers(dns)
    return members.collect{ getUser(it) }.findAll{ it }.sort{ User u -> "$u.lastName  $u.firstName"}
}

Upvotes: 2

Views: 2241

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96385

This is a Java feature called varargs, Groovy also supports it. It lets the method accept multiple parameters without making the caller package them into a data structure first. The arguments get bundled into an array before being passed into the method:

groovy:000> def foo(String... stuff) {
groovy:001>   println(stuff.class)
groovy:002>   for (s in stuff) {
groovy:003>     println(s)
groovy:004>   }}
===> true
groovy:000> foo('a','b','c','d')
class [Ljava.lang.String;
a
b
c
d
===> null
groovy:000> foo('q')
class [Ljava.lang.String;
q
===> null

class [Ljava.lang.String; means it's an array (as opposed to a java.util.ArrayList).

Upvotes: 2

Related Questions