What a static array is
An array stores several values of the same type under one name. A static (or fixed) array has its size decided when it is created, and that size never changes. If you need to add or remove items later, you want a list instead, which a later lesson covers.
Kotlin has no special array syntax. Arrays are objects, and you create them by calling a function. Which function you call depends on whether you have the values yet.
Creating an array of a given size
When you know how many items you need but not their values, ask for an array of that size:
val zeros = IntArray(5)
val names = arrayOfNulls<String>(3)
println(zeros.contentToString())
println(names.contentToString())
[0, 0, 0, 0, 0]
[null, null, null]
IntArray(5) makes five integers, all starting at 0. The other primitive arrays work the same way: DoubleArray starts with 0.0, BooleanArray with false.
arrayOfNulls<String>(3) makes room for three strings, but there are no strings yet. Every slot holds null, so the type of the array is Array<String?>: the ? says each element may be missing. You have to fill the slots before you can use them as ordinary strings.
Creating an array with values
When you already know the values, list them in arrayOf, or in intArrayOf for integers:
val fruits = arrayOf("mango", "kiwi", "grapefruit")
val ages = intArrayOf(14, 32, 50, 21)
The array's size is the number of values you list: 3 for fruits, 4 for ages. Kotlin infers the element type from the values, so fruits is an Array<String>.
Common mistakes and gotchas
Array<Int>andIntArrayare different types.IntArraystores plainintvalues and is the usual choice for numbers.Array<Int>, whicharrayOf(1, 2, 3)creates, stores boxed objects. A function that takes anIntArraywon't accept anArray<Int>.- Printing an array doesn't show its contents.
println(fruits)prints a type name and a hash code, something like[Ljava.lang.String;@1b6d3586. UsecontentToString()to see the elements. valdoesn't freeze the array. It stops the variable from being pointed at a different array, but the items can still be changed.- The size can't grow. An array made with
IntArray(20)has 20 slots for good. There is noaddon an array. - Nullable slots need care. Reading
names[0].lengthon anarrayOfNulls<String>array doesn't compile: the compiler reports that only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver.
The exercise
- Create
numbers. The task asks for integers and a fixed size of 20, which is exactly whatIntArray(20)gives: 20 elements, all 0. - Create
fruits. The values are known, so usearrayOfand list the three strings in the order given.
val numbers = IntArray(20)
val fruits = arrayOf("mango", "kiwi", "grapefruit")
Nothing prints here: the exercise only creates the arrays. To see them, add println(numbers.size), which prints 20, and println(fruits.contentToString()), which prints [mango, kiwi, grapefruit].
More ways to build and use arrays
The other primitive array types follow the pattern of IntArray: DoubleArray(2) holds [0.0, 0.0] and BooleanArray(2) holds [false, false]. Each has a matching builder with values, such as doubleArrayOf(1.5, 2.5).
If every slot should start with a computed value rather than a default, give the constructor a lambda. The lambda receives the index of each slot and returns its value:
val evens = Array(3) { it * 2 }
println(evens.contentToString())
[0, 2, 4]
Two variables, one array
An array is an object, so assigning it to another variable copies the reference, not the elements. After val b = a, both names refer to the same array, and a change through b shows up through a. To get an independent array, call copyOf():
val a = intArrayOf(1, 2, 3)
val b = a
b[0] = 99
val c = a.copyOf()
c[0] = 5
println(a.contentToString())
println(c.contentToString())
[99, 2, 3]
[5, 2, 3]
Choosing between an array and a list
Pick an array when the number of items is known and stays the same, such as the twelve months of a year, the pixels of a fixed-size image or the results of a fixed number of tests. Pick a list when items come and go. Arrays also give you the primitive types IntArray, DoubleArray and so on, which store plain numbers without wrapping each one in an object.
A good habit is to create the array with the right size from the start. If you find yourself wanting to add one more item, that is the sign to switch to a list.
Key takeaways
- An array holds items of one type, and its size is fixed when it is created.
IntArray(n)createsnzeros;arrayOfNulls<T>(n)createsnempty slots.arrayOf(...)andintArrayOf(...)create an array from listed values.- Use
contentToString()to print the elements.