vararg with other arguments

There is a possibility that we will be asked to create a function with an integer vararg along with two integer variables. See the following example:

fun trickyVararg(vararg list: Int, a : Int, b: Int){
var total = 0
for (item in list){
total += item
}

println("Total $total")
println("a = $a , b = $b")
}

fun main (args: Array<String>) {
trickyVararg(1,2,3,4,5)
}

The first three values (1,2,3) are for  vararg list; parameter a is assigned with value 4 and parameter b is assigned with value 5. However, the compiler will throw the following errors:

Kotlin: No value passed for parameter 'a'
Kotlin: No value passed for parameter 'b'

vararg list is declared first in the function signature, and the compiler considers the all input for vararg list. This problem can be solved by declaring vararg as the last function argument:

fun trickyVararg(a : Int, b: Int, vararg list: Int){

var total = 0
for (item in list){
total += item
}
println("Total $total")
println("a = $a , b = $b")
}
fun main (args: Array<String>) {
trickyVararg(4,5,1,2,3)
}

The compiler will now assign the first two values to the a and b variables, and the rest will be assigned to vararg list. Declaring vararg at the end of the function signature is good practice, but it is not necessary. It can be declared at the beginning, but we must ensure that we call the rest of the variables by name:

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

fun main (args: Array<String>) {
trickyVararg02(1,2,3,a=4, b=5)
}

Notice that by declaring the parameters' names in the function call, the compiler does not complain about missing values.

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

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