Convert Kotlin Array to Java varargs
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:
Kotlin invocation:
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:
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.
Was this article helpful?