1. Overview
In this quick tutorial, we’ll look at how we can initialize an array in Kotlin.
2. arrayOf Library Method
Kotlin has a built-in arrayOf method that converts the provided enumerated values into an array of the given type:
val strings = arrayOf("January", "February", "March")
3. Primitive Arrays
We can also use the arrayOf method with primitive values.
However, Kotlin will autobox the primitive values to their corresponding object wrapper classes which will have detrimental performance implications. To avoid this overhead Kotlin has wide support for primitive arrays. There are dedicated arrayOf methods for the following types: double, float, long, int, char, short, byte, boolean.
We can easily initialize a primitive int array using its dedicated arrayOf method:
val integers = intArrayOf(1, 2, 3, 4)
4. Late Initialization With Indices
Sometimes we don’t want to define the array’s values at instantiation. In this case, we can create an array of null values.
After instantiation, we can access and set the fields of the array. There are several ways to do this, but a common way is to use Kotlin’s indices property*.* This property returns a range of valid indices for the array. We can use the range to access and set the values of the array in a for loop.
Let’s initialize our array with square numbers using this approach:
val array = arrayOfNulls<Number>(5)
for (i in array.indices) {
array[i] = i * i
}
5. Creating Empty Arrays
We can also create empty arrays in Kotlin. Let’s look at how to create an empty array of a given type in Kotlin:
val emptyStringArray = emptyArray<String>()
This creates an empty Array
6. Generating Values With an Initializer
Primitive arrays and object arrays both have constructors that accept an initializer function as a second parameter. This initializer function takes the index as the input parameter, translates it into the appropriate value using the function, and inserts it into the array.
We can initialize an array with square numbers in one line:
val generatedArray = IntArray(10) { i -> i * i }
As mentioned, this kind of constructor is also available for object arrays:
val generatedStringArray = Array(10) { i -> "Number of index: $i" }
7. Initialize IntArray From IntRange
Kotlin provides the IntRange class to conveniently define a closed range of integer values:
val intRange = 1..10 // includes both start and end values
However, if we want to create an IntArray object from IntRange, neither IntRange offers any direct transformation method nor IntArray gives a constructor that accepts an IntRange object. As a result, first, we need to convert the IntRange object to a List and then use the toIntArray() method to get an IntArray object:
val intRange = 1..10
val intArray = intRange.toList().toIntArray();
assertEquals(10, intArray.size)
var index = 0
for (element in intRange) {
assertEquals(element, intArray[index++])
}
Although we’ve got this working, this approach is not memory-efficient, especially for ranges containing many integer values.
As an improvement over this approach, we can create an extension function for IntRange that could give us an IntArray without making any intermediate object.
Now, let’s go ahead and implement the toIntArray() extension function for the IntRange class:
fun IntRange.toIntArray(): IntArray {
val result = IntArray(this.count())
var index = 0
for (element in this) {
result[index++] = element
}
return result
}
Finally, let’s verify that our memory-efficient approach is working correctly:
val intRange = 1..10
val intArray = intRange.toIntArray()
assertEquals(10, intArray.size)
var index = 0
for (element in intRange) {
assertEquals(element, intArray[index++])
}
Great! It looks like we’ve nailed this.
8. Conclusion
In this article, we saw how to initialize arrays in Kotlin. We discovered a wide range of support for primitive arrays. We also observed how we can use the array constructor with an initializer function to write concise code. Lastly, we explored a memory-efficient way to initialize an IntArray from an IntRange object.
As always, the code is available over on GitHub.