Using named parameters and vararg at the same time

I was trying to create a function, where the first parameter is optional, followed by a list of vararg parameters.
Unfortunately although in theory this was possible, in practice it was not convinient at all.

The definition was something like

fun run(out: (String) → Unit = {}, vararg args: String): Int

Unfortunately calling this function was not quite elegant.
I was expecting, if I omit the first parameter, to jump directly to the vararg part. But no, it still marks the first given parameter as the parameter with the default value, as if it wasn’t marked as default.

And if I want to use named parameters, there is no way I can use the vararg parameters as is, without some magic with the expand operator etc

Even swapping the variable location, does not make it better.

Am I missing something? Or this is not supported (yet) ?

You can just reverse the order of the parameters like this:

fun run(vararg args: String, out: (String) -> Unit = {}): Int

then you can just call function without any problems:

run("a", "b", "c") // with default function
run("a", "b", "c") { println(it) } // with supplied function
1 Like

Indeed, I manage to make it work and call it with the proposed syntax.

This time I was also lucky using the syntax

run("a", "b", "c", out = { println(it) }

Though, the syntax proposed confused me - how/why the lambda is defined like thi, outside the proper definition?
And what if it wasn’t a lambda but any other random variable, or even two lambdas?

Thanks for your patience!

Well, you can somewhat mix named parameters with varargs. You can lookup more information about them in documentation.

What I presented to you was an example of convention with inputing function expression as a last function parameter, just as explained here:
https://kotlinlang.org/docs/reference/lambdas.html