Skip to main content
An array in Kotlin is a mutable, fixed-size collection of elements of a uniform type, represented by the Array<T> class. On the JVM, Kotlin arrays are backed by standard Java arrays. A critical distinction in Kotlin’s type system is that arrays are invariant. This means Array<String> is not considered a subtype of Array<Any>, preventing ArrayStoreException runtime errors that can occur in Java.

Array Instantiation

Kotlin provides several standard library functions and constructors to instantiate arrays: 1. Using arrayOf and arrayOfNulls The most direct method is using factory functions. arrayOf creates an array with specified elements, while arrayOfNulls creates an array of a given size filled with null values.
2. Using the Array Constructor The Array class constructor takes two parameters: the size of the array and an initialization lambda function (Int) -> T that returns the initial value for each index.

Primitive Arrays

Using Array<Int> or Array<Double> results in the boxing of primitive types on the JVM (e.g., Integer[]), which incurs memory and performance overhead. To represent unboxed primitive arrays (e.g., int[]), Kotlin provides specialized classes: ByteArray, ShortArray, IntArray, LongArray, FloatArray, DoubleArray, BooleanArray, and CharArray. These classes have no inheritance relationship with the Array<T> class but expose identical methods and properties.

Access and Modification

Array elements are accessed and modified using the indexed access operator [], which the Kotlin compiler translates into calls to the get() and set() member functions.

Interoperability and the Spread Operator

When calling Java methods that accept variable-length arguments (vararg), or Kotlin functions with vararg parameters, an existing array cannot be passed directly as a single argument. It must be unpacked using the spread operator (*).
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More