ProgrammingKotlin Developer

How does 'vararg' work in Kotlin? Describe the rules of passing, limitations, interaction with common patterns, and typical difficulties when combining with named and regular arguments.

Pass interviews with Hintsage AI assistant

Answer.

The vararg keyword in Kotlin allows a function to accept a variable number of arguments. This is equivalent to arrays in Java, but with additional syntactic sugar.

Rules and limitations:

  • Regular syntax: fun foo(vararg numbers: Int)
  • The vararg argument must be the last parameter of the function (if there are parameters after it, they must be named when called).
  • You can pass both individual values and an array (using the spread operator *).
  • A function with vararg can be called without passing values for that argument.

Code Example

fun printAll(vararg strings: String) { for (s in strings) println(s) } val arr = arrayOf("a", "b", "c") printAll("one", "two") // will work printAll(*arr) // spread (unpacks the array)

Trick Question.

Is it possible to declare two 'vararg' parameters in one function or place 'vararg' not last?

Answer: No, in Kotlin you can only use one vararg in a function declaration, and it must always be last among positional arguments. If you add a regular parameter after it, it can only be passed by name.

Example:

fun foo(vararg items: String, prefix: String) // Compilation error! // Correct: fun foo(vararg items: String, vararg items2: Int) // Compilation error! // Works: fun foo(vararg items: String, prefix: String = "[default]") foo("a", "b", prefix = "->")

Examples of real errors due to lack of knowledge of the nuances of the topic.


Story

A young programmer mistakenly thought that it was possible to declare two vararg parameters at once. The function architecture was built in such a way that the separation occurred at several levels of the call. This led to a chain of refactorings — the logic of received data had to be reviewed and all calls rewritten.


Story

In an Android project, the spread operator * was forgotten when passing an array to a function with a vararg parameter: printAll(arr) instead of printAll(*arr). As a result, instead of printing the elements, the array was output as a single string with an object address, which logically caused the application to behave strangely.


Story

In a function with vararg and additional named parameters fun foo(vararg a: Int, b: Int), calls through positional arguments were misinterpreted: the compiler could not determine where the list for vararg ends and where the b argument begins, leading to compilation errors. They decided to explicitly use argument names for such parameters.