Let me know what is the importance of varargs in Kotlin, if there is any document or some useful links. Please share.
1 Answers
The vararg
parameters allow for functions that accept variable number of arguments in a natural way, i.e. without creating an array or a collection first, filling it with the items, and only then passing it, compare:
If there were no vararg
parameters:
val items = ArrayList<String>().apply { add("foo"); add("bar"); add("baz") }
qux(items)
With vararg
:
qux("foo", "bar", "baz")
This is particularly useful for initializing collections and other containers, and there are numerous functions for that in kotlin-stdlib
, such as arrayOf(...)
, listOf(...)
, setOf(...)
, mapOf(...)
, sequenceOf(...)
and more.
To see the usages in kotlin-stdlib
, search for the word 'vararg' in the API reference pages (there's a lot in packages kotlin.collections
, kotlin.text
).
Basically, if there is a function accepting a collection that a user might frequently call with only a few items (and choose the items right before the call), it makes sense to provide a vararg
overload for that function.

- 140,743
- 39
- 371
- 326