Variable function arguments

Variable function arguments are a feature that allows you to pass multiple argument values to a single function argument. This feature is also available in Java, and a function that accepts variable function arguments has three dots after the parameter type, like this:

public int sumNumbers(int... nums)

In Kotlin, you can have the same functionality if you apply the vararg keyword before a parameter name:

fun sumNumbers(vararg num: Int): Int {
var result = 0
for (i in num) {
result += i
}
return result
}

Now, we can call this function and supply an arbitrary number of arguments to it:

val result = sumNumbers(1, 2, 3, 4, 5)

When calling a function with variable arguments, the compiler packs them into an array. What happens when you create an array yourself and want to pass it to a function with Varargs? This is where Kotlin differs from Java. Java lets you pass the array directly as an argument, but Kotlin doesn't. Kotlin requires that an array is explicitly unpacked. This is the responsibility of the spread operator, *. The next example shows how you'd call the previous function when unpacking the array:

val nums = intArrayOf(1, 2, 3, 4, 5)
val result = sumNumbers(*nums)
..................Content has been hidden....................

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