Kotlin Arrays

Arrays in Kotlin are fixed-size collections that store elements of the same type in contiguous, indexed slots.

What Is an Array?

An array is a container that holds a fixed number of values of a single type. Once created, an array's size cannot change, but the values at each index can be reassigned. Kotlin represents arrays with the Array<T> class, and it also provides specialized classes like IntArray, DoubleArray, and BooleanArray for primitive types to avoid boxing overhead.

Creating Arrays with arrayOf

The simplest way to build an array is the arrayOf() function, which infers the element type from the values you pass in. For primitive arrays, Kotlin offers dedicated builders such as intArrayOf(), doubleArrayOf(), and charArrayOf(), which store raw primitives instead of boxed objects for better performance.

Creating arrays

fun main() {
    val fruits = arrayOf("Apple", "Banana", "Cherry")
    val numbers = intArrayOf(10, 20, 30, 40)
    val mixed: Array<Any> = arrayOf(1, "two", 3.0, true)

    println(fruits.joinToString())
    println(numbers.joinToString())
    println(mixed.joinToString())
}

Indexing and Updating Elements

Array elements are accessed using square-bracket notation, and indices start at 0. The last valid index is always size - 1. Reading an out-of-range index throws an ArrayIndexOutOfBoundsException at runtime, so it is good practice to check against the array's size property before accessing an index that comes from user input or a calculation.

Reading and writing by index

fun main() {
    val colors = arrayOf("Red", "Green", "Blue")

    println("First: ${colors[0]}")
    println("Last: ${colors[colors.size - 1]}")

    colors[1] = "Yellow"
    println(colors.joinToString())
}

Building Arrays with a Lambda

The Array(size) { index -> ... } constructor builds an array by calling a lambda once per index, which is useful when the values follow a pattern rather than being typed out by hand.

Array constructor with a lambda

fun main() {
    val squares = Array(6) { i -> i * i }
    println(squares.joinToString())
    // Output: 0, 1, 4, 9, 16, 25
}

Common Array Properties and Functions

  • size - the number of elements the array holds
  • indices - a range from 0 to size - 1, handy for loops
  • first() / last() - shortcuts for the boundary elements
  • contains(value) - checks whether a value exists in the array
  • sortedArray() - returns a new, sorted copy without modifying the original
  • sort() - sorts the array in place
FunctionPurposeMutates Original?
sort()Sorts elements in ascending orderYes
sortedArray()Returns a new sorted arrayNo
reverse()Reverses element order in placeYes
copyOf()Creates a new array with copied elementsNo
Note: Array<Int> and IntArray are not the same type. arrayOf(1, 2, 3) produces a boxed Array<Int>, while intArrayOf(1, 2, 3) produces an unboxed IntArray. Prefer the primitive variants for large numeric datasets.
Note: Kotlin arrays have a fixed size once created. If you need a resizable collection, use a MutableList instead - lists support add() and removeAt(), which arrays do not.

Exercise: Kotlin Arrays

What does the size property of a Kotlin array return?