Kotlin Variable Arguments (`vararg`) Tutorial

beginner
20 min

Kotlin Variable Arguments (vararg) Tutorial

Welcome to our deep dive into Kotlin's Variable Arguments (vararg). This powerful feature makes it easier to work with multiple arguments in a flexible and efficient way. By the end of this tutorial, you'll be able to harness the power of vararg in your own projects! 🎯

Table of Contents

  1. Introduction to Variable Arguments (vararg)
  2. Understanding the vararg Keyword
  3. Creating Functions with Variable Arguments
  4. Practical Examples with Variable Arguments
  5. Quiz: Variable Arguments

<a name="intro"></a>

1. Introduction to Variable Arguments (vararg)

In Kotlin, Variable Arguments (vararg) are used to pass multiple arguments of the same type to a function. This feature allows us to create flexible functions that can handle any number of arguments, making our code more versatile and easier to maintain. 💡

<a name="vararg-keyword"></a>

2. Understanding the vararg Keyword

The vararg keyword is used before the function parameter that can accept multiple arguments. This parameter is treated as an array in the function body. Here's a simple example:

kotlin
fun greet(vararg names: String) { for (name in names) { println("Hello, $name!") } }

In this example, the greet function takes any number of String arguments using vararg. Inside the function, we loop through the names array and greet each one individually.

<a name="create-function"></a>

3. Creating Functions with Variable Arguments

You can create functions with variable arguments for various purposes, such as summing numbers, concatenating strings, or handling different types of collections. Here's an example of a function that calculates the sum of all numbers passed as arguments:

kotlin
fun sum(vararg numbers: Int): Int { var total = 0 for (number in numbers) { total += number } return total }

In this example, the sum function takes any number of Int arguments using vararg. Inside the function, we loop through the numbers array and calculate the total.

<a name="examples"></a>

4. Practical Examples with Variable Arguments

Let's explore some real-world examples of using Variable Arguments in Kotlin:

a) Summing Numbers

kotlin
fun main() { val numbers = intArrayOf(1, 2, 3, 4, 5) val total = sum(*numbers) println("The sum of the numbers is: $total") }

b) Concatenating Strings

kotlin
fun main() { val names = arrayOf("John", "Doe", "Smith") val fullName = joinNames(*names) println("The full name is: $fullName") } fun joinNames(vararg names: String): String { var result = names[0] for (i in 1 until names.size) { result += " " + names[i] } return result }

<a name="quiz"></a>

5. Quiz: Variable Arguments

Quick Quiz
Question 1 of 1

What is the Kotlin keyword used to accept multiple arguments of the same type in a function?

That's all for now! Keep practicing with Variable Arguments to make your functions more adaptable and efficient. Happy coding! 📝 ✅