Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Can you use named arguments for varargs?

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?

like image 923
Jire Avatar asked Aug 14 '16 09:08

Jire


People also ask

How does Kotlin define Varargs?

In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.

How do you use Varargs in Kotlin?

Variable number of arguments (varargs)Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.

What is named argument in Kotlin?

The arguments that are passed using name while calling a function are called named arguments. While calling the function we must use the name of the formal argument to which we are passing the actual argument value.

How many Varargs can we have in a function Kotlin?

vararg in Kotlin In Java, the vararg parameter has to be the last one in the parameters list — so you can only have one vararg parameter.


2 Answers

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

complicated(numbers = *intArrayOf(1, 2, 3, 4, 5)) 
like image 105
Alexander Udalov Avatar answered Oct 17 '22 17:10

Alexander Udalov


It can be worked around by moving optional arguments after the vararg:

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

Then it can be called like this:

complicated(1, 2, 3, 4, 5) complicated(1, 2, 3, hard = true) complicated(1, easy = true) 

Note that trailing optional params need to be always passed with name. This won't compile:

complicated(1, 2, 3, 4, true, true) // compile error 

Another option is to spare vararg sugar for explicit array param:

fun complicated(easy: Boolean = false, hard: Boolean = true, numbers: IntArray) = {}  complicated(numbers = intArrayOf(1, 2, 3, 4, 5)) 
like image 38
Vadzim Avatar answered Oct 17 '22 19:10

Vadzim