Part 05 / Topic 5 of 8
vararg: a variable number of arguments
vararg lets a parameter accept zero, one, or many arguments of the same type at the call
site, packed into an array inside the function.
fun sum(vararg numbers: Int): Int {
var total = 0
for (n in numbers) total += n
return total
}
fun main() {
println("Sum of 3: ${sum(10, 20, 30)}")
println("Sum of 1: ${sum(5)}")
println("Sum of 0: ${sum()}")
}
Sum of 3: 60
Sum of 1: 5
Sum of 0: 0
When the values already live in an array, the spread operator (*) hands the whole array to
a vararg parameter in one go, instead of listing each element by hand:
fun subtotal(vararg prices: Double): Double {
var total = 0.0
for (p in prices) total += p
return total
}
val prices = doubleArrayOf(99.0, 149.0, 499.0)
println("Subtotal: ₹${subtotal(*prices)}")
Subtotal: ₹747.0
A function can take a fixed parameter before a vararg one too:
fun describeOrder(orderId: String, vararg items: String) {
println("Order $orderId: ${items.joinToString(", ")}")
}
Order ORD1001: Rice, Dal, Oil
🔍 Going deeper: a function may only have one
varargparameter, and convention puts it last -- but it doesn't strictly have to be. Put a fixed parameter after thevarargone, and every argument meant for that trailing parameter must be passed by name, since there is no position left for it to claim:fun describe(vararg items: String, label: String) { ... } describe("a", "b", "c", label = "fruits") // compiles; label MUST be named hereDropping
label =and just appending"fruits"as a fourth plain argument does not silently fold it intoitems-- verified by actually doing it, the compiler instead refuses the call outright:error: no value passed for parameter 'label'. describe("a", "b", "c", "fruits") ^^^^^^^^Once a parameter follows a
vararg, the compiler simply won't let a positional argument reach it at all --label =is the only way in, not a convenience.
Full program: examples/05_vararg.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.