Call overloaded vararg function

Given following two methods:

fun findAny(name: String): String? {
    return findAny(???) // <- delegate to findAny(vararg)
}
fun findAny(vararg names: String): String?

How can the overloaded vararg function be properly invoked by the first function with the single name parameter?
findAny(*arrayOf(name)) looks like wrapping the variable in an array to spread it immediately afterwards. Is there another more concise way?

Just delete the first one? Seems it doesn’t add much. If however the first one does something different probably it’s worthwhile to change its name.

At the JVM level, the vararg param is an array; the * merely tells the compiler to send it as such without further wrapping.

So no, if you want to call the vararg version, there’s no alternative to creating an array (explicitly or not). (Which, of course, removes the only benefit of a single-object version which just calls the other.)

But having two overloads which can take the same param is inherently risky — other code too could be unable to call the right version. (You can also get into a situation where adding/removing a method could cause other code to behave differently without causing any compile errors.)

So as al3c says, if you need both versions, it’d be safer to give them different names.

Use named arguments

findAny(names = arrayOf(name))

IIRC though, this will still do the spreading sadly. There was a YouTrack Issue somewhere to optimize this

Optimize what exactly? As @gidds said, this function receives an array, so I’m not sure how we could avoid creating it.

BTW, I think “spread” is a misleading word here. The thing is that we don’t spread anything. We just pass an array.

Great. Thanks for this hint.
It would be great if you could also provide the KT issue :slight_smile:

Thanks for clarification i.e. *arrayOf(name) is quite ok then.

Edit: or findAny(name, *emptyArray()):smiley:

This is different. In this case we didn’t provide a single array which we can simply pass. We provided an item and an array to be merged into a single array. Of course, Kotlin compiler could recognize the emptyArray function and provide a special treatment, but I believe it doesn’t do this in 2.0.20.