Vararg parameter
Sometimes, the number of parameters is not known in advance. In such cases, we can add a vararg
modifier to a parameter. It allows the function to accept any number of arguments. Here is an example, where the function is printing the sum of multiple integers:
fun printSum(vararg numbers: Int) { val sum = numbers.sum() print(sum) } printSum(1,2,3,4,5) // Prints: 15 printSum() // Prints: 0
Arguments will be accessible inside the method as an array that holds all the provided values. The type of the array will correspond to a vararg
parameter type. Normally we would expect it to be a generic array holding a specified type (Array<T>
), but as we know, Kotlin has an optimized type for arrays of Int
called IntArray
, so this type will be used. Here, for example, is the type of the vararg
parameter with the type String
:
fun printAll(vararg texts: String) { //Inferred type of texts is Array<String> val allTexts...