Passing Variable Arguments to a Function in Kotlin
Last Updated :
27 Jan, 2023
There are a lot of scenarios in which we need to pass variable arguments to a function. In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body. In this article, 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.
Example
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 as vararg, as in the following example:
Kotlin
fun main (args: Array<String>) {
someMethod ( "as", "you", "know", "this", "works")
}
fun someMethod (vararg a: String) {
for (a_ in a) {
println(a_)
}
}
Also, if you already have an array of values, you can directly pass it using the * spread operator:
Kotlin
fun main(args: Array<String>) {
val list = arrayOf ("as", "you", "know", "this", "works")
someMethod (*list)
}
fun someMethod (vararg a: String) {
for (a_in a) {
println(a_)
}
}
So basically, vararg tells the compiler to take the passed arguments and wrap them into an array. The spread operator, on the other hand, simply tells the compiler to unwrap array members and pass them as separate arguments, The spread operator-that is, *-is put just before the name of the array being passed in. However, obviously, one may always need to pass on other arguments, named arguments, and so on. In the following example code, we try to pass another argument other than vararg:
Kotlin
fun main (args: Array<String>) {
val list = arrayof( "as", "you", "know", "this", "works")
someMethod ( 3, *list)
}
fun someMethod (b: Int, vararg a: String) {
for (a_ in a) {
println(a_)
}
}
In the next example, the first argument is similar to the vararg type, but it works:
Kotlin
fun main (args: Array<String>) {
someMethod ("3", "as", "you", "know", "this", "works")
}
fun someMethod (b: String, vararg a: String) {
printIn ("b: " + b)
for (a_ in a) {
println (a_)
}
}
Output:
b: 3
as
you
know
this
works
So usually, vararg is the last argument passed, but what if we want to pass other arguments after vararg? We can, but they have to be named. That is why the following code will not compile:
Kotlin
fun main (args: Array<String>) {
someMethod ("3", "as", "you", "know", "this", "works", "what")
}
fun someMethod (b: String, vararg a: String, c: String) {
printin ("b: " + b)
for (a_ in a) {
println(a_)
}
println("c: " + c)
}
It does not compile because the last string passed in it is considered part of vararg, and the compiler throws an error because we did not pass the value of c. To do it correctly, we need to pass c as a named argument, just as shown here:Â
Kotlin
fun main (args: Array<String>) {
someMethod ("3", "as", "you", "know", "this", "works", c = "what")
}
fun someMethod (b: String, vararg a: String, c: String) {
printin ("b: " + b)
for (a_ in a){
println(a_)
}
println ("c: " + c)
}
Output:
b: 3
as
you
know
this
works
c: what
The vararg modifier tells the compiler to take all comma-separated arguments and wrap them into an array, while *-that is the spread operator-unwraps elements of the array and passes them as arguments.
What if we want the first argument to have a default value, like in this example:
Kotlin
fun main (args: Array<String>) {
someMethod ("3", "as", "you", "know", "this", "works")
}
fun someMethod (b: String = "x", vararg a: String) {
printin ("b: " + b)
for (a_ in a){
println (a_)
}
}
We want all arguments to be considered as part of vararg, but the compiler reads the first argument as b. In this case, naming the passed arguments can solve the problem:
Kotlin
fun main (args: Array<String>) {
someMethod (a = *arrayOf ("3", "as", "you", "know", "this", "works"))
}
fun someMethod (b: String = "x", vararg a: String) {
println ("b: " + b)
for (a_ in a){
println (a_)
}
}
In the preceding code, the compiler understands that the value of b is not passed, and it takes the default value. Similarly, if you want to have two vararg in your function, you will need to pass named arguments.
Similar Reads
How to Specify Default Values in Kotlin Functions? In Kotlin, you can provide default values to parameters in a function definition. If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default arguments are used. But If you come from the Java world,
4 min read
How to Pass a Function as a Parameter to Another in Kotlin? Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with. In fact, many of the Kotlin library's functions are high order, such as NBQ. In Kotlin
4 min read
Working with Anonymous Function in Kotlin In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kot
3 min read
How to Write swap Function in Kotlin using the also Function? also is an extension function to Template class which takes a lambda as a parameter, applies contract on it, executes the lambda function within the scope of calling object, and ultimately returns the same calling object of Template class itself. Swapping two numbers is one of the most common things
3 min read
Suspend Function In Kotlin Coroutines Prerequisite: Kotlin Coroutines on Android The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a
4 min read
Kotlin | Default and Named argument In most programming languages, we need to specify all the arguments that a function accepts while calling that function, but in Kotlin, we need not specify all the arguments that a function accepts while calling that function, so it is one of the most important features. We can get rid of this const
7 min read
Kotlin Function Variations With Examples While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one. Defining a function in Kotlin: Visibility modifier fun functionName (argument name: type name, ...): return type{ ..... // function body ..... return value } Normally, It is the proper way f
3 min read
"lateinit" Variable in Kotlin In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they can't be used as identifiers. For example, asbreakclasscontinuelateinit "latei
3 min read
Transform a List Using Map Function in Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Local Functions in Kotlin The idea behind functions is very simple: split up a large program into smaller chunks that can be reasoned more easily and allow the reuse of the code to avoid repetition. This second point is known as the DRY principle: Don't Repeat Yourself. The more the number of times you write the same code, t
5 min read