— Kotlin, Java, Varargs — 1 min read
Interoperability between Kotlin and Java is a cornerstone of Kotlin's design. A common scenario is passing a Kotlin array to a Java method that accepts varargs. This article explains how to accomplish this using Kotlin's spread operator.
Kotlin's spread operator, denoted by *
, is used to pass an array to a function expecting varargs. It essentially "spreads" an array into individual elements.
Suppose we have a Java method that accepts varargs:
1public void printNames(String... names) {2 // Java method implementation3}
In Kotlin, we can pass an array to this method as follows:
1val names = arrayOf("Alice", "Bob", "Charlie")2printNames(*names)
Here, *names
spreads the names
array into individual strings, which are then passed as varargs to the printNames
method.
If you have a Kotlin list instead of an array, first convert it to an array using toTypedArray()
before using the spread operator.
1val nameList = listOf("Alice", "Bob", "Charlie")2printNames(*nameList.toTypedArray())
While convenient, it's important to note that using the spread operator can have performance implications, especially for large arrays, as it involves creating a copy of the array elements.