Search code examples
listgroovyparameters

Complete groovy list of parameters


I have a function with an optional list of parameters :

cleanFolders(String... folders) {
    other_function_called(param1,param2,param3)
}

This function calls another function which take exactly three parameters.

So, I want to use the list of parameters folders to call this other function :

  • if there is only one element in folders list, I call
other_function_called(folders[0],"none","none")
  • if there are two elements :
other_function_called(folders[0],folders[1],"none")
  • and for three elements :
other_function_called(folders[0],folders[1],folders[2])

How I can do this properly (not using many disgracious "if else") ?

Thanks


Solution

  • as Jeff writes, you can use * to unpack the varargs array.

    However, this will give you MissingMethodException if the number of arguments is not matching.

    For this case you could create a new array starting with the available values, that is then filled up with the remaining default values, so that unpacked it just matches the right number of arguments.

    def spreadArgs = args + ["none"] * (3 - args.size())
    other_function_called(*spreadArgs)