278

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 to pass an ArrayList to a varargs method parameter?

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
robie2011
  • 3,678
  • 4
  • 21
  • 20

1 Answers1

547

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()
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • And how to convert back? – lacas May 24 '18 at 06:22
  • 1
    @Iacas What do you mean by "convert back"? A `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. – Dario Seidl Nov 04 '18 at 21:31
  • 11
    Note that this has a very high-performance penalty. https://sites.google.com/a/athaydes.com/renato-athaydes/posts/kotlinshiddencosts-benchmarks check Varargs, or https://medium.com/@BladeCoder/exploring-kotlins-hidden-costs-part-2-324a4a50b70#da53 – svkaka Nov 11 '18 at 21:58
  • 2
    Is there any way to avoid using spread operator and pass some array or list to a method that accepts `vararg`? – Wackaloon Mar 29 '19 at 09:23
  • @DarioSeidl He means: What if we have varargs of string, and we wish to pass to a function that expects an array of strings? – android developer Oct 07 '19 at 10:41
  • @SimonNinon is right, `someVarargMethod(*myList.toTypedArray())` work fine – Williaan Lopes Jun 16 '20 at 04:31