Explain Codes LogoExplain Codes Logo

Convert Kotlin Array to Java varargs

java
list-to-array
nullable-concerns
primitive-types
Alex KataevbyAlex Kataev·Oct 4, 2024
TLDR

To call a Java method with varargs from Kotlin, simply apply the spread operator (*) before your array. This spreads the array out into individual elements, just as varargs expects.

Java method:

public void javaMethod(String... args) { /* ... */ }

Kotlin invocation:

val kotlinArray = arrayOf("element1", "element2") javaMethod(*kotlinArray) // Spread array love to Java ☕️❤️

The * operator allows your array to be unpacked and served to the Java method as varargs.

When dealing with lists

Possibly, you have a Kotlin List, not an Array, and you need it in varargs. For this purpose, first convert the List to an Array using toTypedArray(), before spreading it:

val kotlinList = listOf("element1", "element2") javaMethod(*kotlinList.toTypedArray()) // listToArray() -- a conversion story 📚

Nullability matters

Nullability may be a concern when converting Kotlin arrays to Java varargs. If your Java method does not anticipate nulls, ensure your Kotlin array doesn’t contain any, or behold the dreaded NullPointerException.

Primitives and varargs

For primitive arrays (e.g., IntArray), you'll need to invoke methods like toIntArray() to obtain an array that can be passed as varargs. Remember, Java and Kotlin view primitive types a bit differently (Int vs int).

Under the hood

Understanding how the spread operator works helps. When you spread an array, Kotlin effectively generates a loop to pass each item individually to the varargs parameter.

Performance peers through the spread operator

Although elegant, the spread operator can create an extra array, hence some overhead. This is less of a concern for modest-sized collections, but for large ones, you might think twice.

Tackling advanced scenarios

For advanced usages, such as generic type varargs or nullability annotations in Java, detailed attention and perhaps more cutting-edge conversions could be required.