Functions and vararg

Kotlin allows programmers to pass arguments separated by commas to the function. These arguments are automatically converted into an array. This is called a vararg, a variable argument. Declare a vararg along with its type in the function declaration:

fun varargString(vararg list : String){
for (item in list){
println(item)
}
}

fun main (args: Array<String>) {
varargString("ett","tva","tre")
varargString("Sat","Sun","Mon")
}

As another example, write a function that takes an integer vararg as a parameter, adds it, and displays the total on the screen:

fun addVararg(vararg list: Int){
var total = 0
for (item in list){
total += item
}
println("Total $total")
}

fun main (args: Array<String>) {
addVararg(1,2,3,4,5,6,7,8,9,10)
}

vararg makes a programmer's life easier, especially when he or she is not sure about how many parameters may be required for one function:

fun add(a: Int, b: Int , c: Int , d: Int, e: Int)
fun add(vararg list : Int)

The first add function is restricted to the limited amount of variables declared in the function signature, but the add function with vararg can operate on all comma-separated values that we will pass to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.84.157