Java – What’s the Kotlin equivalent of Java’s String[]

javakotlin

I see that Kotlin has ByteArray, ShortArray, IntArray, CharArray, DoubleArray, FloatArray, which are equivalent to byte[], short[], int[],char[], double[], float[] in Java.

Now I'm wondering, is there any StringArray equivalent to Java's String[]?

Best Answer

There's no special case for String, because String is an ordinary referential type on JVM, in contrast with Java primitives (int, double, ...) -- storing them in a reference Array<T> requires boxing them into objects like Integer and Double. The purpose of specialized arrays like IntArray in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java int[] instead of Integer[]).

You can use Array<String> (and Array<String?> for nullables), which is equivalent to String[] in Java:

val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")

See also: Arrays in the language reference