kotlinvariadic-functions

Kotlin varargs to array


There is a function I want to call in a third-party library:

fun foo(strings: Array<String>)

The array strings is only used for reading, i.e. foo doesn't write to it.

Now, I want to write a function of my own, like this:

fun bar(vararg vstrings: String) {
    do some things...
    foo(vstrings)
    do some more things...
}

But the foo(vstrings) call results in a compilation error: argument type mismatch: actual type is 'Array<CapturedType(out String)>', but 'Array<String>' was expected.

I can't change the signature of foo. How can I pass this vararg parameter as an array?


Solution

  • This is because the vararg parameter is of type Array<out String>, not Array<String>. See also the specification. I think this is to prevent you from modifying the array's elements, which is almost always incorrect.

    You can create a copy of the array then pass the copy to foo.

    fun bar(vararg vstrings: String) {
        foo(Array(vstrings.size) { vstrings[it] })
    }
    

    In Kotlin/JS, you can call vstrings.copyOf() directly, but this is no available on other platforms for some reason.