Kotlin Array Guide

Array is one of the fundamental and simplest data structures in the programming languages in which each of the elements is identified by an index/key. In most of the programming languages, data in an array is stored linearly in the volatile memory.

In Kotlin, arrays are considered as basic data types and represented by Array class. The Array class contains useful functions like get(), set() and properties like the size.

Read Also : How to Create and Run First Kotlin Project

Creating and Accessing an Array

In Kotlin, there are three ways to create an array that will be explained thoroughly along with the code examples with its output that will help you understand better.

1. Kotlin Array arrayOf() Example: Using the library function

Kotlin provides easy functions to create an instance of an array. One of these functions is arrayOf(). The get() function is used to retrieve a value at index passed as a parameter. The set() function is used to assign the required value to a specified index. Both values are required as a parameter.
Let’s see different ways to use it efficiently in the following code snippet

    fun main(){
 
        // initializing integer array with [1,2,3,4,5]
        val numbers = arrayOf(1,2,3,4,5) 

        /* you may noticed that there is no data type mentioned 
           in the above declaration as kotlin implicitly declare 
           the data type according to the values passed in the
           arrayOf() function */

        println (numbers.size) // gives size of numbers array

        println(numbers.get(1)) // returns 2

        println(numbers[1]) // equivalent to numbers.get(1)
    }

Output:
5
2
2

If you want to just declare an array and assign values later, you can use arrayOfNulls(). Traversing the whole array is very common for a lot of functions. Kotlin provides easy and efficient syntax to solve this problem. Let's look at the different ways to traverse the array.

    fun main(){
 
        /* creating array of size 5 with each value 
        as null */
        val names = arrayOfNulls<String>(5
 
        // assigning "Java" to 0th index of names array
        names.set(0,"Java"
 
        /* assigning "Kotlin" to 1st index equivalent 
        to names.set(1,"kotlin") */
        names[1] = "Kotlin" 

        names[2] = "C"

        names[3] = "Swift"

        names[4] = "Dart"

        /* to traverse whole array, you can use for loop 
        with 'in' operator */
        for(element in names){

            print("${element},")

        }

    }

Output:
Java,Kotlin,C,Swift,Dart,

2. Using Array Constructor

The Array constructor accepts the size of the array and a lambda expression to initialize the array.

    fun main(){

        /* create an integer array of size 10 and for every
        index 'i' store the value in it using (i+1) * 5 */

        val tableOfFive = Array<Int>(10,{i -> (i+1) * 5})

        // An easy way to traverse whole array is using forEach function

        // forEach function also requires a lambda function

        // here the lambda function take every value in the array and print it

        tableOfFive.forEach { value -> print("${value},") }

    }

Output:
5,10,15,20,25,30,35,40,45,50,

3. Using Specialized Array

Kotlin also provides built-in arrays for the primitive data type (Short, Byte, Int) to avoid using templates (e.g Array) and also has better performance than the same array which is using the template.

There is IntArray() class for Integer, ByteArray() class for Byte, DoubleArray() for Double, LongArray() for Long.

To create their instances use intArrayOf(), byteArrayOf(), doubleArrayOf(), longArrayOf() respectively.

These classes are not the child of the Array class but have the same properties and functions as an Array class.


    fun main(){

        // Integer array of size 5 with values [1,2,3,4,5]

        val numbers = intArrayOf(1,2,3,4,5)

        val longNumbers = doubleArrayOf(1.5,2.5,3.5,4.5,5.5)

        var sum : Double = 0.0

        /* traversing through both the arrays 
        and adding each value to sum */

        numbers.forEach { value ->  sum += value }

        longNumbers.forEach { value -> sum += value }

        println(sum)

    }

Output:
32.5

Avoiding ArrayIndexOutOfBoundException

A very common programming mistake is trying to retrieve/set a value at an index that doesn’t exist. For example, if you declare an array of size 5 and try to access the 5th index (6th element), the program throws ArrayIndexOutOfBoundException. Let's try to reproduce this problem using the following code snippet

fun main(){

        // array of size 3 initialized with [1,2,3]
        val array = intArrayOf(1,2,3)
 
        // printing last element of array  
        println(array[2])
 
        /* trying to get a value at index which is 
        not in range of the array */ 
        println(array[3])

    }

Output:
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3out of bounds for length 3
    at MainKt.main(main.kt:5)
    at MainKt.main(main.kt)

The above program threw ArrayIndexOutOfBoundsException because we tried to access the 3rd index (4th  element) which does not exist. There are 2 ways to solve this problem. The first way is to use getOrElse() function which if the index does not exist return the default value provided through lambda function in the parameter.

    fun main(){

        // array of size 3 initialized with [1,2,3]

        val array = intArrayOf(1,2,3)

        // printing last element of array

        println(array[2])

        /* try to get value of value at 3rd index if it results 
        in ArrayIndexOutOfBoundsException use the lambda function 
        to get default value */

        /* here the lambda function {0} always return 0 as 
        in kotlin almost everything is an expression */

        println(array.getOrElse(3,{0}))

    }

Output: 
3
0

The second way is to use the getOrNull() function. It returns null if the index does not exist. This method is not as good as the first method but, in the end, it depends on your usage and logic.

    fun main(){

        // array of size 3 initialized with [1,2,3]

        val array = intArrayOf(1,2,3)

        // printing last element of array

        println(array[2])

        /* try to get value of value at 3rd index if it results 
        in ArrayIndexOutOfBoundsException use the lambda function
        to get default value */ 
 
        /* here the lambda function {0} always return 0 as 
        in kotlin almost everything is an expression */ 

        println(array.getOrNull(3))

    }

Output:
3
null

To keep updated with the new tutorials and guidelines regarding Kotlin, stay tuned to our blog. If you have any further queries regarding Kotlin Array, do let me know in the comments section.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry