Kotlin

Kotlin Varargs Examples

A function may receive a variable number of parameters of the identical type using the Kotlin functionality known as varargs (variable-length arguments). It offers flexibility whenever the precise number of arguments is uncertain or unpredictable. With a function statement, the “vararg” term that is used before the parameter type denotes that the argument may take zero or more parameters of that kind. The varargs parameter functions as an array inside the body of the function which enables you to traverse over the arguments or carry out additional actions.

By removing the need to explicitly generate an array or provide the number of parameters when invoking the method, this feature makes the code simpler and easier for developers. In this guide, we will discuss the uses of the Kotlin vararg feature with the help of some code examples. Let’s begin with the code examples now.

Syntax:

To define a varargs parameter in Kotlin, the “vararg” keyword is placed before the parameter type in the function declaration. Within the function, the varargs argument acts like a collection or array which lets us iterate over the parameters or execute other actions on them. In the following syntax code, the yourfunction() function accepts multiple integers as arguments. The numbers parameter is defined with the “vararg” keyword which indicates that it can receive zero or more integers.

fun yourfunction(vararg numbers: Int) { // function logic }

 

When invoking a function with varargs, the arguments can be provided individually, separated by commas. The yourfunction() function can handle any number of the provided arguments.

yourfunction(1, 2, 3, 4, 5)

 

Example 1:

To demonstrate the use of varargs in Kotlin code, we provided the code for Kotlin varargs. The drive of the snippet is to display the functionality of varargs in Kotlin. The code defines a function called “Display” that accepts a varargs parameter “Arr” of type Int. The function can accept a variable number of arguments of the specified type through the use of the vararg keyword before the parameter type.

Within the function, it iterates over the elements in “Arr” using a “for” loop and prints each value on a new line using the “println” function of Kotlin. In the main function, the “Display” function is invoked with multiple integer arguments: 4, 5, 1, 7, and 9. These arguments are passed to the varargs parameter “Arr”. In this case, the “Display” function can receive several arguments. The “for” loop within the function allows the values to be processed one by one, and the println function prints each value on a separate line.

fun Display(vararg Arr: Int) {
    for (v in Arr) {
        println(v)
    } }
fun main() {
    Display(1, 2, 3, 4, 5)
}

 

As the output demonstrates, the utilization of Kotlin varargs to handle multiple input values which are 4, 5, 1, 7, and 9 are displayed each on a new line:

Example 2:

The previous example displays the use of varargs to receive and display the same type of data on the console separately. Now, we utilize the varargs in another example to demonstrate how different operations can be performed on specific values. The purpose of this code example is to reveal the practice of varargs in Kotlin in a different way and showcase a simple arithmetic operation.

The following provided code demonstrates a function named “Subtract” that takes a varargs parameter “Arr” of type Int. The purpose of this function is to subtract all the values that are passed as arguments from an initial value of 0 and return the final result. Within the function, a variable “s” is initialized to 0 to store the subtraction result.

Then, a loop iterates over each element “n” in the “Arr” varargs array. For every member, the value of variable “n” is subtracted from “s”. The “for” loop continues until all the members in the array collection are dealt with. In the main function, the “Subtract” function is invoked with the 1, 8, 2, 9, and -2 arguments. The return value from the function call is assigned to the variable “r”. Finally, a string is printed using the println function which displays the “Result after Subtraction: ” message followed by the value of “r”. By providing a variable number of arguments to the “Subtract” function, it performs the subtraction operation on all the provided values and returns the final result.

fun Subtract(vararg Arr: Int): Int {
    var s = 0
    for (n in Arr) {
        s -= n  }
    return s    }
fun main() {
    val r = Subtract(1, 8, 2, 9, -2)
    println("Result after Subtraction: $r")
}

 

The output after the execution of this snippet must be “-18” as shown in the following image:

Example 3:

Let’s begin with another Kotlin code example containing vararg. This code is utilized to concatenate multiple strings using a function with varargs. The code snippet consists of two parts: the Concat()function and the main function. The Concat method permits the concatenation of any number of string arguments that are passed to it. The Concat function is defined with a varargs parameter “s” of type String. It uses the built-in joinToString() function of Kotlin to concatenate the strings in the “s” array without any separator (specified by separator = “”). It joins these strings together which results in a single string. You can cast off any separator here, i.e. comma or space.

The joinToString() function converts the array of strings into a single string by joining them together. In the main function, the “Concat” function is called with three string arguments: “Ko”, “tl”, and “in!”. The main function demonstrates the usage of the “Concat” function by calling it with three string arguments and printing the concatenated result. These strings are passed as individual arguments due to the use of varargs. The return value of the “Concat” function is stored in the variable “r”. The println statement in the main function prints the result of the concatenation by interpolating the value of “r” into the “Result: $r” string. The output is “Kotlin!”.

fun Concat(vararg s: String): String {
    return s.joinToString(separator = "")
}
fun main() {
    val r= Concat("Ko", "tl", "in!")
    println("Result: $r")
}

 

This code showcases the convenience and flexibility that is provided by Kotlin’s varargs feature for concatenating the strings as per the following output:

Conclusion

Using the varargs syntax in Kotlin simplifies the handling of functions that need to handle a flexible number of arguments which provides convenience and flexibility to the developers. Within the Kotlin code examples for varargs, we demonstrated how it is helpful in simply displaying the values at new lines, how a specific operation can be performed on specific types of data, and how the strings can be concatenated.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.