How can I convert my Kotlin Array to a varargs Java String[]?
val angularRoutings =
arrayOf<String>("/language", "/home")
// this doesn't work
web.ignoring().antMatchers(angularRoutings)
How can I convert my Kotlin Array to a varargs Java String[]?
val angularRoutings =
arrayOf<String>("/language", "/home")
// this doesn't work
web.ignoring().antMatchers(angularRoutings)
There’s the spread operator which is denoted by *.
The spread operator is placed in front of the array argument:
antMatchers(*angularRoutings)
For further information, see the documentation:
When we call a
vararg-function, we can pass arguments one-by-one, e.g.asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with*):
Please note that the spread operator is only defined for arrays, and cannot be used on a list directly. When dealing with a list, use e.g.toTypedArray() to transform it to an array:
*list.toTypedArray()
vararg expects individual elements, and *array is the Kotlin way to say "treat this array as individual elements for that purpose". Within the vararg-function the vararg parameter will be an array anyway. To convert individual elements to an array you can use arrayOf(...), but you don't need that in this case.vararg?First of all, I want to say that @s1m0nw1's answer is awesome. Kotlin's spread operator (or *) lets you decompose an array into a list of individual elements when passing it to a function. However, I'd like to show you how to convert Kotlin's Array to Java's Varargs without spread operator. Here's the code:
fun toListFrom(vararg severalStrs: String): List<String> {
return severalStrs.asList()
}
fun main() {
val elements = arrayOf("He","l","lo"," ","Kot","li","n!")
val concatenation = toListFrom(elements.reduce { a, b -> a + b })
val result = concatenation.first()
println(result) // Hello Kotlin!
}
And this is what my code will look like if I use * spread operator.
fun concatenate(vararg severalStrs: String): String {
return severalStrs.reduce { a, b -> a + b }
}
fun main() {
val elements = arrayOf("He","l","lo"," ","Kot","li","n!")
val concat = concatenate(*elements)
println(concat) // Hello Kotlin!
}
Tested on Kotlin 2.0.0 Playground.