Blog / October 13, 2018 / 2 mins read / By Suneet Agrawal

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.

Variables

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(<b>vararg</b> 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 &lt;T&gt; asList(<b>vararg</b> input: T): List&lt;T&gt; {
    val result = ArrayList&lt;T&gt;()
    for (item in input) // input 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(<b>vararg</b> 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)
Comments