Vararg parameters in Functions


What’s the Varargs parameter?

Varargs is an acronym for Variable Arguments. In Java, a method argument can accept an arbitrary number of values. This argument for accepting a variable number of values is called varargs.

Sometimes we need a function that can transfer n parameters and determine the value of n in runtime. We can obtain Kotlin by defining a parameter of a function as vararg. We can transfer the n number of parameters to a vararg variable of a defined datatype or a generic type.

How do the parameters pass through Kotlin?

In Kotlin, parameters in the function definition can be given default values. If the function is called with passed arguments, those arguments will be used as parameters. However, the default arguments are used if the function is called without passing the argument (s).

How do you beat Varargs in Kotlin?

In Kotlin, you can transfer a variable argument 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 ) within the function body.

  • Vararg keyword: vararg is used in a method declaration to denote variable number parameters will be accepted.
  • Spread Operator: An asterisk (*) before an array used in function calls to "unfold" contents as individual parameters.