Lesson 6

Understanding Varargs in Kotlin Functions

Topic Overview and Actualization

Hello and welcome! Today, we will delve into an intriguing topic—the varargs in Kotlin. This feature enables us to pass a variable number of arguments to a function, in a manner similar to a shopping list of varying lengths. We will discuss varargs, their syntax, rules in Kotlin, and how they operate within Kotlin functions. An exciting journey awaits us, so let's get started!

Introduction to Variable Arguments (Varargs) in Kotlin

Let's demystify varargs. They grant us the ability to pass any number of arguments to a function, resembling an array that bypasses the need for array creation by allowing the direct passage of arguments. The keyword vararg is your ticket to expressing variable arguments in Kotlin:

1fun greet(vararg names: String) { 2 // code... 3}

Now, you are prepared to call greet with any number of argument strings or even no argument:

1greet("Alice", "Bob", "Charlie") 2greet()
Using Varargs in Functions

Now it's showtime for varargs in your functions. As a refresher, the vararg keyword can capture a flexible quantity of arguments. A function can include only one vararg parameter, which must be positioned last if additional parameters exist. Here's an example of a function that prints a greeting before a variable quantity of names:

1fun printNames(greeting: String, vararg names: String) { 2 for (name in names) { 3 println("$greeting, $name") 4 } 5} 6 7printNames("Hello", "Alice", "Bob", "Charlie") // It will print "Hello, Alice", "Hello, Bob" and "Hello, Charlie" on separate lines.
Spread Operator

Sometimes we have an existing array instance in Kotlin, and we want to pass it to a function accepting a vararg. In those situations, to decompose the array to a vararg, we can use the spread operator:

1fun printNames(vararg names: String) { 2 for (name in names) { 3 println(name) 4 } 5} 6 7val names = arrayOf("Alice", "Bob", "Charlie") 8printNames(*names)

The * in front of the names argument is the spread operator.

Quick Lesson Summary and Upcoming Practice Exercises

Congratulations on mastering varargs in Kotlin! We've explored in-depth— understanding varargs, declaring them with vararg, and using them in function definitions. We also learned how to pass both, individual arguments and an array, to a function expecting a vararg parameter. Engaging practice exercises are up next to solidify this newfound knowledge. So warm up your coding fingers and get ready—happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.