Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 134 ยท Collections

Arrays

Learn Kotlin arrays: arrayOf, Array(n) { }, IntArray and other primitive arrays, fixed size, contentToString, copyOf, equality, 2D arrays, vararg interop and arrays vs lists, with runnable code.

An array is a fixed-size block of elements stored next to each other in memory. Arrays are the lowest-level collection on the JVM: lists, sets and maps are built on top of them. In day-to-day Kotlin you reach for a List first, and for good reasons that you will see in this lesson. But arrays are everywhere in real programs: main(args: Array<String>), Java libraries, byte buffers, image data, vararg parameters and performance-sensitive loops all use them, so you must be able to read and write them confidently.

You will learn the two array families (Array<T> and the primitive arrays such as IntArray), how to create, read, change and print them, why == on arrays surprises people, how to copy and convert them, and when a list is the better choice. You should be comfortable with Lists and Loops first.

Creating arrays

Kotlin arrays are objects of the class Array<T>. Create one with arrayOf, or with a size and an initializer lambda:

Kotlin Creating arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 3, Alan, [0, 1, 4, 9, 16], [null, null, null], 0 and Ada, Alan Turing, Grace. Arrays are mutable (you can assign to names[1]) but their size is fixed at creation. There is no add or remove. arrayOfNulls<String>(3) makes an array of three null slots, typed Array<String?>.

Printing an array

The default toString of an array is not helpful. Try it:

Kotlin println on an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints true: the plain text form is the type code [Ljava.lang.Integer; followed by @ and a hash, which is useless and changes from run to run. Use contentToString() (or joinToString(), or toList()) when you want to see the elements. This is the single most common array mistake for beginners.

Primitive arrays

An Array<Int> stores boxed Integer objects. For numbers, Kotlin offers special classes that map to Java's primitive arrays: IntArray, LongArray, DoubleArray, FloatArray, ShortArray, ByteArray, CharArray and BooleanArray. Each stores raw values with no boxing, so they use far less memory and are faster.

Kotlin IntArray and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [5, 3, 9], [0, 0, 0, 0], [0, 10, 20, 30, 40], [false, false, false], kot, 17, 9, 5.666666666666667 and [3, 5, 9]. IntArray(4) starts with zeros (false for BooleanArray). a.sort() sorts the array in place, unlike sorted() on a list, which returns a new one.

Array versus IntArray

They are different types and do not mix:

Kotlin Array<Int> and IntArray are different types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects the call with main.kt:5:19: error: argument type mismatch: actual type is 'Array<Int>', but 'IntArray' was expected. Convert with boxed.toIntArray() (and back with toTypedArray()). Prefer IntArray for numeric work and Array<T> for objects.

Reading, writing and looping

Square brackets call get and set. The indices property and withIndex() work just as for lists:

Kotlin Looping over an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see 108, 4 15 23 , odd 15 at 2, odd 23 at 4, [100, 8, 15, 16, 23, 40], [40, 23, 16, 15, 8, 100] and [8, 15, 16]. Compound assignment such as data[i] -= 2 works on array elements. Functions ending in Array (reversedArray, sliceArray) return arrays, while reversed() and slice() return lists.

An invalid index throws at run time:

Kotlin ArrayIndexOutOfBoundsException (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The loop prints 1, 2, 3 and then crashes with Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3. The classic off-by-one: valid indexes are 0 to size - 1, so the condition must be i < small.size. Better yet, loop with for (x in small) or small.indices and the bug cannot happen. Use getOrNull(i) for a safe lookup.

Equality, copying and conversion

Arrays do not override equals. == compares identity, not contents:

Kotlin Comparing and copying arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is false, true, true, [99, 2, 3], [99, 2, 3], [99, 77, 3], [99, 2, 3, 0, 0], [2, 3], [99, 2, 3, 4], [99, 2, 3] and [99, 2, 3]. Remember the rules:

  • Use contentEquals, contentHashCode and contentToString for contents. Data classes that contain an array property inherit this trap: their generated equals compares the arrays by identity, so IDEs warn about it.
  • val alias = a shares one array; assignment never copies. Use copyOf() for a copy. copyOf(n) resizes, padding with default values or truncating.
  • a + 4 returns a new array.
  • The copy is shallow: for an Array of objects, both arrays point to the same objects.

Two-dimensional arrays

An array of arrays is a grid. Create each row separately:

Kotlin A grid as an array of arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output rows are 0 1 2 3, 4 5 -1 7 and 8 9 10 11, followed by 59, [3, 7, 11] and [[0, 1, 2, 3], [4, 5, -1, 7], [8, 9, 10, 11]]. The total is 6 + 15 + 38 = 59, and max() picks the largest value of each row. contentDeepToString prints nested arrays; contentToString would show the inner arrays as type codes.

Create every row inside the initializer lambda, as above, so each row is its own array. If you build one val row = IntArray(4) outside and put it in every slot (for example with Array(3) { row }), all rows are the same array and writing to grid[0][0] changes every row.

Arrays and vararg

A vararg parameter is an array inside the function. The spread operator * passes an existing array as separate arguments (see Varargs and the Spread Operator):

Kotlin vararg and arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get none: 0 numbers, [], three: 3 numbers, [1, 2, 3], spread: 2 numbers, [7, 8], mixed: 4 numbers, [0, 7, 8, 9] and 0 (no command-line arguments). Spreading copies the array, so changing the original afterwards does not affect the function's numbers. The main function can take args: Array<String>, which holds the command-line arguments, or no parameters at all in modern Kotlin.

Arrays versus lists

Array List
Size fixed read-only list: fixed; MutableList: grows
Mutability elements can always be changed List cannot be changed through the interface
Primitives IntArray etc. without boxing List<Int> boxes each element
== / toString identity / type code contents
Generics invariant, reified covariant (List<out E>)
Rich API good richer, and more idiomatic

Arrays are invariant: an Array<Int> is not an Array<Number>, because that would allow storing a Double into an array of Ints. Lists are read-only and covariant, so a List<Int> can be used as a List<Number>. More on that in Variance.

Use a List by default: it prints, compares and composes well. Use an array when:

  • a Java API requires one (for example String.format(fmt, *args) or a byte[] parameter);
  • you need a large fixed block of numbers and want to avoid boxing (IntArray, ByteArray, DoubleArray);
  • you want fast random writes in a hot loop;
  • you receive args: Array<String> in main.
Kotlin Moving between arrays and lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [pear, fig, apple], [apple, fig, pear], [pear, fig, apple], 6 and [4, 3, 5]. sortedArray() returns a sorted copy, leaving the original untouched, while words.sort() would reorder words itself. Most collection functions (map, filter, sum, sortedBy, ...) work on arrays too, and map returns a list.

Pitfalls summary

  • Printing an array with println(arr) shows [I@1b2c3d-style text; use contentToString().
  • == on arrays compares identity; use contentEquals.
  • Assignment shares the array; use copyOf() to duplicate.
  • The size cannot change; if you need add, use a MutableList or ArrayList.
  • Array<Int> and IntArray are not interchangeable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does intArrayOf(1, 2) == intArrayOf(1, 2) evaluate to?

    Arrays do not override equals. Use contentEquals to compare contents.
  2. 2. Which call prints the elements of val a = intArrayOf(1, 2, 3) readably?

    println(a) prints a type code and hash. contentToString() gives [1, 2, 3].
  3. 3. Which is true about the size of a Kotlin array?

    Arrays have a fixed size. Use a MutableList for a growing collection.
  4. 4. Why can IntArray be faster and smaller than Array<Int>?

    IntArray maps to Java's int[], whereas Array<Int> holds Integer objects.
  5. 5. What does the * do in describe("x", *values)?

    The spread operator passes each array element as its own argument to a vararg parameter.

Summary

  • Arrays have a fixed size and mutable elements; create them with arrayOf, Array(n) { } and the primitive builders such as intArrayOf and IntArray(n).
  • IntArray, DoubleArray and the other primitive arrays avoid boxing; they are different types from Array<Int>.
  • Use contentToString(), contentEquals() and contentDeepToString(); println, == and toString on arrays are identity-based.
  • copyOf, copyOfRange, sliceArray and + create new arrays; assignment shares one.
  • *array spreads an array into a vararg parameter.
  • Prefer List by default and reach for arrays when an API, performance or main requires them.

Next: Collection Transformations