kotlin-types-arrays.md

#Arrays

Last modified: 01 April 2025

An array is a data structure that holds a fixed number of values of the same type or its subtypes. The most common type of array in Kotlin is the object-type array, represented by the Array class.

If you use primitives in an object-type array, this has a performance impact because your primitives are boxed into objects. To avoid boxing overhead, use primitive-type arrays instead.


#When to use arrays

Use arrays in Kotlin when you have specialized low-level requirements that you need to meet. For example, if you have performance requirements beyond what is needed for regular applications, or you need to build custom data structures. If you don't have these sorts of restrictions, use collections instead.

#Benefits of Collections vs Arrays

Note: The only way to add or remove elements from an array is to create a new array each time, which is very inefficient.
kotlinvar riversArray = arrayOf("Nile", "Amazon", "Yangtze")

// Using the += assignment operation creates a new riversArray,
// copies over the original elements and adds "Mississippi"
riversArray += "Mississippi"
println(riversArray.joinToString())
// Nile, Amazon, Yangtze, Mississippi

#Create arrays

To create arrays in Kotlin, you can use:

  1. Functions: such as arrayOf(), arrayOfNulls(), or emptyArray().
  2. The Array constructor.

#Using functions

kotlin// Creates an array with values [1, 2, 3]
val simpleArray = arrayOf(1, 2, 3)
println(simpleArray.joinToString())
// 1, 2, 3

// Creates an array of a given size filled with null elements
val nullArray: Array<Int?> = arrayOfNulls(3)
println(nullArray.joinToString())
// null, null, null

// Creates an empty array
var exampleArray = emptyArray<String>()
// Or with explicit type on the left
var exampleArray2: Array<String> = emptyArray()

#Using the Array constructor

The Array constructor takes the array size and a function that returns values for array elements given its index:

kotlin// Creates an Array<Int> that initializes with zeros [0, 0, 0]
val initArray = Array<Int>(3) { 0 }
println(initArray.joinToString())
// 0, 0, 0

// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5) { i -> (i * i).toString() }
asc.forEach { print(it) }
// 014916

Indices start from 0 in Kotlin.


#Nested arrays

Arrays can be nested within each other to create multidimensional arrays. They do not have to be the same type or size.

kotlin// Creates a two-dimensional array
val twoDArray = Array(2) { Array<Int>(2) { 0 } }
println(twoDArray.contentDeepToString())
// [[0, 0], [0, 0]]

#Access and modify elements

Arrays are always mutable. Use the indexed access operator [] to interact with elements:

kotlinval simpleArray = arrayOf(1, 2, 3)
simpleArray[0] = 10
println(simpleArray[0].toString()) // 10
Important: Arrays in Kotlin are invariant. You cannot assign an Array<String> to an Array<Any>. To allow this, use Array<out Any>.

#Work with arrays

#Pass variable number of arguments

Use the spread operator (*) to pass an array to a vararg parameter. It passes each element as an individual argument.

kotlinfun main() {
    val lettersArray = arrayOf("c", "d")
    printAllStrings("a", "b", *lettersArray)
    // abcd
}

fun printAllStrings(vararg strings: String) {
    for (string in strings) {
        print(string)
    }
}

#Compare arrays

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

kotlinval simpleArray = arrayOf(1, 2, 3)
val anotherArray = arrayOf(1, 2, 3)

println(simpleArray.contentEquals(anotherArray)) // true

#Transform arrays


#Convert arrays to collections

TargetFunctionNote
List.toList()Converts array to a List.
Set.toSet()Converts array to a Set (removes duplicates).
Map.toMap()Only for arrays of Pair<K,V>.
kotlinval pairArray = arrayOf("apple" to 120, "banana" to 150)
println(pairArray.toMap())
// {apple=120, banana=150}

#Primitive-type arrays

To avoid the overhead of boxing, use these specialized classes. They have no inheritance relation to Array but share the same functions.

Primitive-type arrayEquivalent in Java
BooleanArrayboolean[]
ByteArraybyte[]
CharArraychar[]
DoubleArraydouble[]
FloatArrayfloat[]
IntArrayint[]
LongArraylong[]
ShortArrayshort[]

Conversion: