How to pass kotlin collection as varagrs?

At first glance, you just need to convert the collection to an array and pass it to the method, but this does not work:

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

No workarounds

+4
source share
1 answer

An Arraycan be passed as an argument varargby adding *to it:

Paths.get("", *toTypedArray) 

It is called the distribution operator , as I already described in another question here .

An instance Listcan be converted to varargas follows:

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

Source: https://habr.com/ru/post/1686381/


All Articles