Cherry
Cherry

Reputation: 33524

How to pass a kotlin collection as varagrs?

At first glance it is needed just convert collection to array and pass it to method but this does not work:

val toTypedArray = Arrays.asList("a", "b").toTypedArray()
Paths.get("", toTypedArray) // <- compilation error here

No workarounds???

Upvotes: 13

Views: 1812

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81859

An Array can be passed as anvararg argument by prepending * to it:

Paths.get("", *toTypedArray) 

It’s called spread operator, as I already described in another answer here.

An instance of List can be converted to vararg as follows:

val listAsArr = 
    listOf("a", "b").toTypedArray()
Paths.get("", *listAsArr) 

Upvotes: 24

Related Questions