Kotlin: Can you use named arguments for varargs?

Jire picture Jire · Aug 14, 2016 · Viewed 10.7k times · Source

For example, you might have function with a complicated signature and varargs:

fun complicated(easy: Boolean = false, hard: Boolean = true, vararg numbers: Int)

It would make sense that you should be able to call this function like so:

complicated(numbers = 1, 2, 3, 4, 5)

Unfortunately the compiler doesn't allow this.

Is it possible to use named arguments for varargs? Are there any clever workarounds?

Answer

Alexander Udalov picture Alexander Udalov · Aug 14, 2016

To pass a named argument to a vararg parameter, use the spread operator:

complicated(numbers = *intArrayOf(1, 2, 3, 4, 5))