TExcelTAD
Home › Kotlin › Kotlin Arrays

Kotlin Arrays

An array stores a fixed number of values of the same type in one variable. You can read and change elements by index, but you cannot add or remove slots once the array is created. (For growable collections you'll use List and MutableList — see the Collections chapter.)

Creating arrays

kotlin · try it yourself
fun main() {
    val fruits = arrayOf("apple", "pear", "plum")
    println(fruits[0])
    println(fruits.size)

    fruits[1] = "mango"          // elements can be changed
    println(fruits.joinToString())
}
apple
3
apple, mango, plum

Indexes start at 0, so the last element is at size - 1.

Way to create Example Result
arrayOf(...) arrayOf(1, 2, 3) [1, 2, 3]
Array(n) { … } Array(4) { it * it } [0, 1, 4, 9]
arrayOfNulls<T>(n) arrayOfNulls<String>(2) [null, null]
emptyArray<T>() emptyArray<Int>() []
intArrayOf(...) intArrayOf(5, 6) primitive int[]
IntArray(n) IntArray(3) [0, 0, 0]

Printing an array

Printing an array directly shows a cryptic JVM identifier, not its contents. Use joinToString() or contentToString():

kotlin · try it yourself
fun main() {
    val squares = Array(5) { i -> i * i }
    println(squares.contentToString())
    println(squares.joinToString(" - "))
}
[0, 1, 4, 9, 16]
0 - 1 - 4 - 9 - 16

Primitive arrays

Array<Int> stores boxed Integer objects. For performance-sensitive number crunching, Kotlin has specialised arrays that map to Java primitive arrays: IntArray, DoubleArray, LongArray, BooleanArray, CharArray and so on.

kotlin · try it yourself
fun main() {
    val temps = doubleArrayOf(18.5, 21.0, 19.5, 23.0)
    println("Average: ${temps.average()}")
    println("Max: ${temps.max()}")
    println("Sum: ${temps.sum()}")

    val counters = IntArray(3)     // [0, 0, 0]
    counters[2] += 5
    println(counters.contentToString())
}
Average: 20.5
Max: 23.0
Sum: 82.0
[0, 0, 5]

Checking and searching

kotlin · try it yourself
fun main() {
    val colors = arrayOf("red", "green", "blue")
    println("green" in colors)
    println(colors.contains("pink"))
    println(colors.indexOf("blue"))
    println(colors.first() + " / " + colors.last())

    val sorted = arrayOf(5, 2, 9, 1).sortedArray()
    println(sorted.contentToString())
}
true
false
2
red / blue
[1, 2, 5, 9]

Out of bounds

Reading an index that doesn't exist throws an exception at runtime. Use getOrNull when an index might be invalid:

kotlin · try it yourself
fun main() {
    val nums = arrayOf(10, 20, 30)
    println(nums.getOrNull(5))
    println(nums[5])
}
null
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3

Comparing arrays

== on arrays compares references (are they the same array object?), not contents. Use contentEquals:

kotlin
val a = arrayOf(1, 2)
val b = arrayOf(1, 2)
a == b                // false
a contentEquals b     // true

Multi-dimensional arrays

An array of arrays forms a grid:

kotlin
val board = Array(3) { CharArray(3) { '.' } }
board[1][1] = 'X'

Tip: In everyday Kotlin, List is used far more often than Array. Arrays are mainly needed for main(args), Java interop and performance-critical code.

Test yourself

What does Array(3) { it * 10 } contain?

  1. [10, 20, 30]
  2. [0, 10, 20]
  3. [3, 30, 300]
  4. [0, 0, 0]

How do you print the elements of an array readably?

  1. println(arr)
  2. println(arr.contentToString())
  3. println(arr.size)
  4. println(*arr)

Can you add a fourth element to an array created with arrayOf(1, 2, 3)?

  1. Yes, with add()
  2. No, arrays have a fixed size
  3. Yes, by assigning arr[3]
  4. Only if it is a var