0
0
Kotlinprogramming~3 mins

Why Vararg parameters in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one function that magically handles any number of inputs without extra work?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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
After
fun add(vararg numbers: Int): Int = numbers.sum()
What It Enables

It lets you create simple, powerful functions that work with any number of inputs without extra code.

Real Life Example

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.

Key Takeaways

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.