Variable number of arguments (vararg) : Kotlin

Sometimes we need a function where we can pass n number of parameters, and the value of n can be decided at runtime. Kotlin provides us to achieve the same by defining a parameter of a function as vararg. We can pass n number of parameters to a vararg variable of the defined datatype or even of a generic type.

This post was originally posted at https://agrawalsuneet.github.io/blogs/variable-number-of-arguments-vararg-kotlin/ and reposted on Medium on 13th Oct 2018.

Let me give you an example.

We need a function which takes n number as inputs and returns the average of all the inputs. If the size of n variables is not fixed, we usually convert it into an array or list and pass it to function.

fun getAverage(numbersList: List<Int>): Float {

var sum = 0.0f
for (item in numbersList) {
sum += item
}
return (sum / numbersList.size)
}
val arrayList = arrayListOf(1, 2, 3, 4)
val result = getAverage(arrayList)

Now, what if the function itself takes n inputs and we don’t need to convert it into an array.

fun getAverage(vararg input: Int): Float {
var sum = 0.0f
for (item in input) {
sum += item
}
return (sum / input.size)
}
val result1 = getAverage(1, 2, 3)
val result2 = getAverage(1, 2, 3, 4, 5)

We can pass n number of inputs to the same function and can get the result back. Inside the function, the parameter is available as an Array object and we can perform all normal array operations on it.

We can even use Template type for vararg.

fun <T> asList(vararg input: T): List<T> {
val result = ArrayList<T>()
for (item in input) // ts is an Array
result.add(item)
return result
}

Only one parameter may be marked as vararg. If a vararg parameter is not the last one in the list, values for the following parameters can be passed using the named argument syntax, or if the parameter has a function type, the value can be passed by passing a lambda outside parentheses.

We can even pass all the elements of an array along with other arguments to a vararg variable. We can use the spread (*) operator to do the same.

fun getAverage(vararg input: Int): Float {
var sum = 0.0f
for (item in input) {
sum += item
}
return (sum / input.size)
}
val array = intArrayOf(1, 2, 3, 4)
val result = getAverage(1, 2, 3, *array)

And we are done. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Reference : Kotlin Docs