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?
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.
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.