How to pass a kotlin collection as varagrs?

2019-02-21 17:01发布

问题:

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

回答1:

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 question here.

An instance of List can be converted to varargas follows:

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