Variable number of arguments in a Kotlin function

In Kotlin there is the possibility to define a function so that it can accept a variable number of arguments with the same data type. This is called a Vararg parameters. This is useful when you don't know exactly how many arguments will be passed to the function. A Vararg parameter is used in the function declaration with the keyword vararg characterized.

Example: Let's assume that we want to pass a series of numbers of data type Int to a function without knowing exactly how many numbers there will be. To represent this case, the following function with a variable number of arguments can help us:

Another example is if we want to have a function that calculates the sum of all the numbers passed to it:

Vararg parameters can also be combined with named arguments. For example, a function can have multiple named arguments and a vararg parameter. In such cases, the vararg parameter is usually placed last in the parameter list.

However, it is not a must, if there are other parameters after a vararg parameter, the values ​​of these parameters are passed via named arguments when the function is called:

Spread operator (*)

Typically, an array is passed to a function as a single argument. In the examples shown above, this would trigger a compilation error. The spread operator (*) helps us pass each element of an array as a separate argument to a function.

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked