Passing variable arguments to a function
There are a lot of scenarios in which we need to pass variable arguments to a function. In Kotlin, we can do that using the vararg
modifier. In this recipe, we will go through all the ways of doing that. We will look at a few examples to demonstrate how to use this feature of Kotlin.
Getting ready
You need to install the preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using an online IDE at https://try.kotlinlang.org/ to compile and run my Kotlin code for this recipe. You can also use IntelliJ IDEA for your development environment.
How to do it...
Let's go through the following steps, where we demonstrate how to pass a variable number of arguments to a function:
- Using
vararg
, we can pass comma-separated arguments to a function, where we have defined the single argument to a method asvararg
, as in the following example...