Kotlin Vararg Parameter

Yağmur Erdoğan
1 min readMay 26, 2021

I want to start by asking a simple question. How would you define a function that takes two integers as input and returns their sum as output?

And we can use this function like this;

But what if we want to sum more than two number? What about 15 parameters? How we can define parameters? a: Int, b: Int, c: Int, d: Int…. I am already tired of it and I just defined 4 parameters🙄

Let’s define this function easily with vararg parameter.

Mmm… It seems to have a single parameter. Has it?

The answer is no. It can have more than one parameter. You can add as many numbers as you want.

You should be careful;

  • A function can only have one vararg parameter.
  • You can add more Integer parameters before vararg parameter. The opposite is not possible.
  • You can also pass Integer array.

🐢 Sources

🍒 🥝 You can access source code from my GitHub! 🐰

--

--