Kotlin Help

Arrays

An array is a data structure that holds a fixed number of values of the same type or its subtypes. Array elements are ordered and accessed by index.

Kotlin provides the Array<T> class and primitive-type arrays.

When to use arrays

Use arrays for interoperability with Java APIs or low-level requirements. For example, if you have performance requirements beyond what is needed for regular applications, or you need to build custom data structures.

For most use cases, prefer collections instead.

Functionality

Arrays

Collections

Size

Fixed

Depends on the type

Read-only variant

No, always mutable

Yes (List and Set)

Adding and removing elements

No native support.
Allocate and copy to a new array

Yes (mutable collections)

Structural equality with ==

No, compares references.
Use .contentEquals() instead

Yes

Primitive values

Primitive-type arrays store values
without boxing

Usually boxed

Java interoperability

Maps to T[]

Maps to java.util.List and
java.util.Set

Functional-style filtering and
transformations

Limited

Extensive

Learn how to convert arrays to collections.

Create arrays

To create arrays, you can use:

Array with values

To create a typed array from a known set of values, use the arrayOf() function. Kotlin infers the type automatically:

fun main() { //sampleStart val simpleArray = arrayOf(1, 2, 3) // Array<Int> println(simpleArray.joinToString()) // 1, 2, 3 //sampleEnd }

Empty array

To create an array with no elements, use the emptyArray() function. You can specify the type of elements on the left-hand or right-hand side of the assignment:

val emptyArrayRight = emptyArray<String>() val emptyArrayLeft: Array<String> = emptyArray()

Learn how to add elements to an array.

Array with nulls

To create an array of a given size filled with null elements, use the arrayOfNulls() function:

fun main() { //sampleStart val nullArray: Array<Int?> = arrayOfNulls(3) println(nullArray.joinToString()) // null, null, null //sampleEnd }

Array constructor

The Array constructor takes the array size and a function that returns values of array elements:

fun main() { //sampleStart val zeroes = Array<Int>(3) { 0 } println(zeroes.joinToString()) // 0, 0, 0 val squares = Array(5) { i -> i * i } println(squares.joinToString()) // 0, 1, 4, 9, 16 //sampleEnd }

Nested arrays

To create a nested or multidimensional array, use an array of arrays. Nested arrays don't have to be the same type or the same size.

fun main() { //sampleStart // Creates a two-dimensional array val twoDArray = Array(2) { Array<Int>(2) { 0 } } println(twoDArray.contentDeepToString()) // [[0, 0], [0, 0]] // Creates a three-dimensional array val threeDArray = Array(3) { Array(3) { Array<Int>(3) { 0 } } } println(threeDArray.contentDeepToString()) // [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] //sampleEnd }

Primitive-type arrays

If you use the Array class with primitive values, the compiler boxes these values into objects. To avoid boxing overhead, you can use dedicated primitive-type arrays. They are not subclasses of the Array<T> class, but they provide a similar set of functions and properties.

Kotlin type

Java equivalent

BooleanArray

boolean[]

ByteArray

byte[]

CharArray

char[]

DoubleArray

double[]

FloatArray

float[]

IntArray

int[]

LongArray

long[]

ShortArray

short[]

To create a primitive-type array, use one of the following options:

  • Constructor functions:

    fun main() { //sampleStart // Creates an Int array of size 5 with the values initialized to zero val primitiveTypeArray = IntArray(5) println(primitiveTypeArray.joinToString()) // 0, 0, 0, 0, 0 // Creates an Int array and takes an initializer function val squares = IntArray(5) { i -> i * i } println(squares.joinToString()) // 0, 1, 4, 9, 16 //sampleEnd }

  • Factory functions:

    fun main() { //sampleStart // Creates an Int array with 5 elements val numbers = intArrayOf(1, 2, 3, 4, 5) println(numbers.joinToString()) // 1, 2, 3, 4, 5 // Creates a Char array with 3 elements val characters = charArrayOf('K', 't', 'l') println(characters.joinToString()) // K, t, l // Creates a Double array with 3 elements val doubles = doubleArrayOf(0.22, 4.16, 0.5) println(doubles.joinToString()) // 0.22, 4.16, 0.5 //sampleEnd }

Work with arrays

Arrays support many of the same operations as collections, including iteration, searching, sorting, and transformations. In Kotlin, you can work with arrays by using them to pass a variable number of arguments to a function or perform operations on the arrays themselves. Find the most common properties and functions in the following table:

Member

Returns

size

The number of elements

indices

The range of valid indices

lastIndex

The last valid index

first() and last()

First and last element

isEmpty() and isNotEmpty()

true if array is empty or not empty

contains()

true if array has the element

This section introduces some of the most commonly used operations.

Access and modify elements

To access and modify elements in an array, use the indexed access operator ([]):

fun main() { //sampleStart val simpleArray = arrayOf(1, 2, 3) val twoDArray = Array(2) { Array<Int>(2) { 0 } } // Accesses the element and modifies it simpleArray[0] = 10 twoDArray[0][0] = 2 // Prints the modified element println(simpleArray[0]) // 10 println(twoDArray[0][0]) // 2 //sampleEnd }

You can also use the fill(element, fromIndex, toIndex) function to replace elements in a range in place. fromIndex is inclusive, and toIndex is exclusive:

fun main() { //sampleStart val arr = IntArray(3) println(arr.joinToString()) // 0, 0, 0 arr.fill(1) println(arr.joinToString()) // 1, 1, 1 arr.fill(0, 0, 2) println(arr.joinToString()) // 0, 0, 1 //sampleEnd }

In Kotlin, arrays are invariant. This means that Array<String> is not a subtype of Array<Any>. This prevents possible runtime type failures. To express covariance, use the Array<out Any> type projection:

fun main() { //sampleStart fun printArr(arr: Array<out Any>) { for (item in arr) print("$item, ") } printArr(arrayOf("k", "t", "n")) // k, t, n, //sampleEnd }

Add and remove elements

Since arrays have a fixed size, they don't support the .add() and .remove() functions. To perform these operations, you need to create a new array. For that, you can use one of the following options:

  • Use the .copyOf function:

    fun main() { //sampleStart var arr = intArrayOf(0, 1, 2) arr = arr.copyOf(arr.size + 1) println(arr.joinToString()) // 0, 1, 2, 0 arr[arr.lastIndex] = 3 println(arr.joinToString()) // 0, 1, 2, 3 //sampleEnd }

  • Use the + or += operators:

    fun main() { //sampleStart var arr = intArrayOf(0, 1, 2) arr += 3 println(arr.joinToString()) // 0, 1, 2, 3 arr = arr + intArrayOf(4, 5) println(arr.joinToString()) // 0, 1, 2, 3, 4, 5 //sampleEnd }

Compare arrays

To compare whether two arrays have the same elements in the same order, use the .contentEquals() and .contentDeepEquals() functions:

fun main() { //sampleStart val simpleArray = arrayOf(1, 2, 3) val anotherArray = arrayOf(1, 2, 3) // Compares contents of arrays println(simpleArray.contentEquals(anotherArray)) // true // Using infix notation, compares contents of arrays after an element // is changed simpleArray[0] = 10 println(simpleArray contentEquals anotherArray) // false //sampleEnd }

Transform arrays

Kotlin has many useful functions to transform arrays. This section highlights some of them. See the complete list in our API reference.

Sum

To return the sum of all elements in an array, use the .sum() function:

fun main() { //sampleStart val sumArray = arrayOf(1, 2, 3) println(sumArray.sum()) // 6 //sampleEnd }

Sort and shuffle

You can sort the elements in the array according to their natural order with the .sort() function or randomly shuffle them with the .shuffle() function:

fun main() { //sampleStart val simpleArray = arrayOf(1, 2, 3) // Randomly shuffles elements simpleArray.shuffle() println(simpleArray.joinToString()) // Sorts elements simpleArray.sort() println(simpleArray.joinToString()) // 1, 2, 3 //sampleEnd }

To get a new sorted array without modifying the original, use the .sortedArray() function instead.

Pass variable number of arguments to a function

In Kotlin, you can pass a variable number of arguments to a function via the vararg parameter. This is useful when you don't know the number of arguments in advance, like when formatting a message or creating an SQL query.

To pass an array containing a variable number of arguments to a function, use the spread operator (*). The spread operator passes each element of the array as individual arguments to your chosen function:

fun main() { val lettersArray = arrayOf("c", "d") printAllStrings("a", "b", *lettersArray) // abcd } fun printAllStrings(vararg strings: String) { for (string in strings) { print(string) } }

For more information, see Variable number of arguments (varargs).

Convert to collections

If you work with different APIs where some use arrays and some use collections, you can convert your arrays to collections and vice versa. For that, use the .toList(), .toSet(), and .toMap() functions. These functions copy the content from your array to the independent copy. They don't reflect subsequent changes to the array.

Convert to List or Set

To convert an array to a List or Set, use the .toList() and .toSet() functions:

fun main() { //sampleStart val simpleArray = arrayOf("a", "b", "c", "c") // Converts to a Set println(simpleArray.toSet()) // [a, b, c] // Converts to a List println(simpleArray.toList()) // [a, b, c, c] //sampleEnd }

Unless you are completely sure that the original array isn't changed or shared elsewhere, don't use .asList() and related as* functions. These functions wrap the original array instead of copying it. Therefore, changes to the array are reflected in the list and vice versa.

fun main() { //sampleStart val simpleArray = arrayOf("a", "b", "c") val list = simpleArray.asList() simpleArray[0] = "d" println(list) // [d, b, c] //sampleEnd }

Convert to Map

To convert an array to a Map, use the .toMap() function.

You can convert only an array of Pair<K,V> to a Map. The first value of a Pair instance becomes a key, and the second becomes a value. If the same key appears more than once, the last value is used.

This example uses the infix notation to call the .to function to create tuples of Pair:

fun main() { //sampleStart val pairArray = arrayOf("apple" to 120, "banana" to 150, "cherry" to 90, "apple" to 140) // Converts to a Map // Fruits are keys, calorie numbers are values // The latest "apple" value overwrites the first one println(pairArray.toMap()) // {apple=140, banana=150, cherry=90} //sampleEnd }

What's next?

30 June 2026