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?
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.
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.
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.
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.
To pass a named argument to a vararg parameter, use the spread operator:
complicated(numbers = *intArrayOf(1, 2, 3, 4, 5))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With