Skip to content
DeveloperMemos

Converting Kotlin Array to Java Varargs

Kotlin, Java, Varargs1 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.

The Spread Operator in Kotlin

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.

Example in Kotlin:

Suppose we have a Java method that accepts varargs:

1public void printNames(String... names) {
2 // Java method implementation
3}

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.

Using Spread Operator with Lists

If you have a Kotlin list instead of an array, first convert it to an array using toTypedArray() before using the spread operator.

Example:

1val nameList = listOf("Alice", "Bob", "Charlie")
2printNames(*nameList.toTypedArray())

Performance Considerations

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.