In Kotlin there is the possibility to define a function so that it can accept a variable number of arguments with the same data type. This is called a Vararg parameters. This is useful when you don't know exactly how many arguments will be passed to the function. A Vararg parameter is used in the function declaration with the keyword vararg characterized.
Example: Let's assume that we want to pass a series of numbers of data type Int to a function without knowing exactly how many numbers there will be. To represent this case, the following function with a variable number of arguments can help us:
fun main() {
printAllNumbers(1, 2, 3, 4, 5)
println()
printAllNumbers(10, 15, 20, 25, 30, 35, 40, 45, 50)
}
fun printAllNumbers(vararg numbers: Int) { // Deklaration der Funktion mit variabler Anzahl an Argumenten
for (number in numbers) { // Innerhalb der Funktion können wir dann auf die übergebenen Zahlen mithilfe einer for-Schleife wie auf ein Array zugreifen
print("$number ")
}
}
Another example is if we want to have a function that calculates the sum of all the numbers passed to it:
fun main() {
val result1 = sumOfAllNumbers(1, 2, 3, 4, 5)
println(result1)
val result2 = sumOfAllNumbers(10, 15, 20, 25, 30)
println(result2)
}
fun sumOfAllNumbers(vararg numbers: Int): Int {
var sum: Int = 0
for (number in numbers) {
sum = sum + number
}
return sum
}
Vararg parameters can also be combined with named arguments. For example, a function can have multiple named arguments and a vararg parameter. In such cases, the vararg parameter is usually placed last in the parameter list.
fun main() {
printWithText("Number", 1, 2, 3, 4, 5)
}
fun printWithText(text: String, vararg numbers: Int) {
for (number in numbers) {
println("$text: $number")
}
}
However, it is not a must, if there are other parameters after a vararg parameter, the values of these parameters are passed via named arguments when the function is called:
fun main() {
printWithText("Begin of sequence", "Number", 1, 2, 3, 4, 5, text3="End of sequence") // Nach vararg-Parameter wird der Wert 'End of sequence' über das benannte Argument 'text3' übergeben
}
fun printWithText(text1: String, text2: String, vararg numbers: Int, text3: String) {
println(text1)
for (number in numbers) {
println("$text2: $number")
}
println(text3)
}
Spread operator (*)
Typically, an array is passed to a function as a single argument. In the examples shown above, this would trigger a compilation error. The spread operator (*) helps us pass each element of an array as a separate argument to a function.
fun main() {
val nums = intArrayOf(1, 2, 3, 4)
numberPlusNumber(*nums, plusNumber = 1) // Mithilfe des Operators '*' werden Elemente aus dem Array 'nums' einzeln an die Funktion 'numberPlusNumber' übergeben
}
fun numberPlusNumber(vararg sequenceOfNumbers: Int, plusNumber: Int) {
for(number in sequenceOfNumbers)
println(number + plusNumber)
}