Limitations of vararg

The vararg parameters are convenient, but they have some caveats:

Defining multiple vararg parameters will result in a compiler error, as in the following example:

// this will not compile
// Error: "Multiple vararg-parameters are prohibited"
fun
helloFunctions(vararg nums: Int, greeting: String, vararg names: String) {
...
}

It's generally a good idea to make a vararg parameter the last parameter in your function, especially if there are other arguments of the same type present. To illustrate why this is important, we can use the following helloFunctions example:

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

Because the vararg parameters are treated as an array once passed, the compiler will attempt to satisfy any vararg parameter requirements before single-parameter values. This can lead to trouble if the compiler can't tell which value belongs to the vararg parameter and which argument should stand on its own. The following example illustrates this issue by attempting to call helloFunctions in various ways that the compiler can't understand:

fun main(args: Array<String>) {
helloFunctions("Hello!")
// error: no value passed for parameter 'greeting'
helloFunctions("Hello!", "Android")
// error: no value passed for parameter 'greeting'
helloFunctions("Hello!", "Android", "Kotlin")
// error: no value passed for parameter 'greeting'
}

In this case, the compiler is looking for any number of passed String arguments, and is then looking for the passed greeting parameter. This is simply not possible unless the calling code is making use of named arguments.

If we go back to our previous example usages, we will now see compiler errors in each case. This is because the compiler doesn't know which passed String parameter is supposed to be the greeting parameter, and therefore treats all String instances as the vararg parameter, which means no value is ever passed for greeting

We can, however, work around this by making use of named parameters, which we will look at in the next section.