Variable number of arguments (vararg) : Kotlin

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.
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)
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)
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
}
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)

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store