How to Use vararg in Kotlin: Syntax and Examples
In Kotlin, use
vararg before a parameter type to allow passing a variable number of arguments to a function. This lets you call the function with zero or more values, which Kotlin treats as an array inside the function.Syntax
The vararg keyword is placed before the parameter name in a function declaration to accept multiple arguments as an array.
- vararg paramName: Type — declares a variable number of arguments of the specified type.
- Inside the function, the
paramNamebehaves like an array ofType. - You can pass zero or more arguments when calling the function.
kotlin
fun printAll(vararg messages: String) {
for (m in messages) println(m)
}Example
This example shows a function using vararg to print any number of strings passed to it.
kotlin
fun printAll(vararg messages: String) {
for (m in messages) println(m)
}
fun main() {
printAll("Hello", "World", "from", "vararg")
printAll("Single argument")
printAll() // no arguments
}Output
Hello
World
from
vararg
Single argument
Common Pitfalls
Common mistakes when using vararg include:
- Trying to declare more than one
varargparameter in a function (only one is allowed). - Passing an array directly without using the spread operator
*. - Confusing
varargwith regular array parameters.
Use the spread operator * to pass an existing array to a vararg parameter.
kotlin
fun printAll(vararg messages: String) {
for (m in messages) println(m)
}
fun main() {
val array = arrayOf("A", "B", "C")
// Wrong: printAll(array) // Error: type mismatch
printAll(*array) // Correct: spread operator used
}Output
A
B
C
Quick Reference
| Concept | Description |
|---|---|
| vararg parameter | Allows passing variable number of arguments as an array |
| Only one vararg | A function can have only one vararg parameter |
| Spread operator (*) | Used to pass an existing array to a vararg parameter |
| Inside function | Vararg parameter behaves like an array |
| Zero arguments | You can call the function with no arguments |
Key Takeaways
Use
vararg to accept a flexible number of arguments in Kotlin functions.Only one
vararg parameter is allowed per function.Use the spread operator
* to pass an array to a vararg parameter.Inside the function, the
vararg parameter acts like an array.You can call a
vararg function with zero or more arguments.