The vararg modifier

We can define any number of parameters for our functions, but sometimes we may not know how many parameters we need to pass when writing the code. For these situations, it's possible to define a function that takes an unspecified number of parameters of the same type. This is achieved using the vararg modifier. Let's see how this is done.

Adding vararg to a parameter definition will change that parameter from Type to Array<Type>, allowing a caller to pass in multiple argument values. In the following code, we've now updated helloFunctions to take a variable number of the name arguments by adding vararg before the name parameter definition:

fun helloFunctions(greeting: String, vararg names: String) {
names.forEach { name ->
println("$greeting $name")
}
}

Because of this update, names is now treated as Array<String> rather than String. Because of this, the function body has then been updated to iterate over each passed name, and print it out using the passed greeting argument. 

Now, to invoke helloFunctions with any number of passed arguments, we can use it as follows:

fun main(args: Array<String>) {
helloFunctions("Hello!", "Android", "Kotlin")
}

When calling a function that uses a vararg parameter, you are free to pass 0, 1, or many arguments for the vararg parameter, as follows:

fun main(args: Array<String>) {
helloFunctions("Hello!")
helloFunctions("Hello!", "Android")
helloFunctions("Hello!", "Android", "Kotlin")
}

Here, we are calling helloFunctions three times with different numbers of arguments. In the first case, we don't pass any name argument, and so the resultant argument array will be empty and therefore nothing will be printed to the console. In the other cases, a greeting will be output for each input name that is passed. While the vararg parameters are useful, they do have their limitations as well.