Skip to main content
A vararg (variable number of arguments) parameter allows a function to accept zero or more arguments of a specified type. Declared using the vararg modifier, it instructs the Kotlin compiler to pack the comma-separated arguments provided at the call site into an array accessible within the function body.

Syntax and Type Mapping

When you declare a vararg parameter of type T, the compiler translates it into an Array<out T> within the function scope.
To prevent the performance overhead of boxing and unboxing, Kotlin optimizes vararg parameters for primitive types. A vararg of a primitive type compiles directly to its corresponding specialized primitive array (e.g., IntArray, DoubleArray, CharArray).

The Spread Operator (*)

If you already have an array and want to pass its contents to a function expecting a vararg parameter, you must unpack the array using the spread operator (*). Passing the array directly will result in a type mismatch, as the function expects individual elements, not the array reference itself.
Note: The spread operator only works with arrays. To pass a List or other Collection, it must first be converted using .toTypedArray().

Parameter Positioning and Resolution Rules

Kotlin enforces specific rules regarding the placement of a vararg parameter within a function signature:
  1. Single Vararg Limit: A function can declare a maximum of one vararg parameter.
  2. Trailing Parameters: While it is conventional to place the vararg parameter at the end of the parameter list, it is not strictly required. However, if parameters follow a vararg, they must be passed using named arguments at the call site to resolve ambiguity.
If a function signature includes a functional parameter (lambda) following a vararg, trailing lambda syntax can be used without explicitly naming the parameter.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More