-1

Let me know what is the importance of varargs in Kotlin, if there is any document or some useful links. Please share.

GadaaDhaariGeek
  • 971
  • 1
  • 14
  • 33
Nishant Gupta
  • 457
  • 3
  • 16

1 Answers1

1

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.

hotkey
  • 140,743
  • 39
  • 371
  • 326