August 2017
Intermediate to advanced
440 pages
10h
English
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 ...
Read now
Unlock full access