What if you could write one function that magically handles any number of inputs without extra work?
Why Vararg parameters in Kotlin? - Purpose & Use Cases
Imagine you want to write a function that adds numbers, but you don't know how many numbers people will give you. You try to write a function for one number, then two numbers, then three numbers, and so on.
This manual way is slow and messy. You have to write many versions of the same function, and if someone gives more numbers than you planned, your code breaks or you have to keep adding more functions.
Vararg parameters let you write one function that accepts any number of arguments. You just say "I accept many values," and Kotlin handles them as a list inside your function. This keeps your code clean and flexible.
fun add(a: Int): Int = a fun add(a: Int, b: Int): Int = a + b fun add(a: Int, b: Int, c: Int): Int = a + b + c
fun add(vararg numbers: Int): Int = numbers.sum()It lets you create simple, powerful functions that work with any number of inputs without extra code.
Think about a shopping app where you want to calculate the total price of any number of items a customer buys. Vararg lets you pass all item prices easily to one function.
Writing many functions for different numbers of inputs is hard and error-prone.
Vararg parameters let one function accept many arguments as a list.
This makes your code simpler, cleaner, and more flexible.