DEV Community

Cover image for Kotlin: Multi-dimensional Arrays
Gourav Khunger for Genics Blog

Posted on • Originally published at genicsblog.com

Kotlin: Multi-dimensional Arrays

At some point of time, we all have worked with arrays. It is a useful data structure to store multiple values of the same type in a single variable. Complex usage of arrays includes storing data in 2D, 3D, or other multidimensional arrays. This allows us to represent things like matrices, grids, and cubes effectively.

In this tutorial, we will specifically focus on declaring, initializing and using 2D, 3D, and other multidimensional arrays in the Kotlin programming language.

Pre-requisites

To understand multi-dimensional arrays and lists in kotlin, you need to have a proper understanding of 1D arrays. I have published an intuitive article about kotlin arrays similar to this one, do read the article before proceeding.

2D Arrays in Kotlin

2D arrays are a convenient way to store grid/board/matrix type of data.

If we dig deep into Kotlin Standard Library, the function arrayOf() is actually returning Array<T> where T is the type of the elements in the array. This effectively means that if we pass in T we get out an array Array<T>.

This means if we pass in arrayOf() into the arrayOf() function, we effectively get out Array<Array<T>> and that is exactly the representation of 2D Arrays!

2D Arrays with pre-defined data

Let's see how to make 2D arrays with predefined values:

val array = arrayOf(
    arrayOf(1, 2, 3),
    arrayOf(4, 5, 6),
    arrayOf(7, 8, 9)
)
Enter fullscreen mode Exit fullscreen mode

This creates a 2D Kotlin array which is a collection of 1D Kotlin arrays. Here's a representation of the array:

General Form:
[[1 2 3], [4,5,6], [7,8,9]]

As a matrix:
1 2 3
4 5 6
7 8 9
Enter fullscreen mode Exit fullscreen mode

Again, these arrays are not type-safe. You can add another data type to the array without any issue. To make it type-safe, we need to declare the type of the array during initialization:

val array = arrayOf<Array<Int>>( // Declaring the type gives error if data types are mixed
    arrayOf(1, 2, 3),
    arrayOf(4, 5, 6, "this string will give error"),
    arrayOf(7, 8, 9)
)
Enter fullscreen mode Exit fullscreen mode

2D arrays with dynamic size

To create 2D lists where we don't have a fixed known size, we use mutableListOf<MutableList<T>>() declaration where T is the data type we expect the inner lists to hold. We don't pass any initial value because the array will be populated using some logic later.

Let's look at it in action:

val list = mutableListOf<MutableList<Int>>()

// The elements within the inner lists can be anything, the numbers below are just an example.

// `repeat()` takes in a number and iterates from 0 to number-1
repeat(4) {
    // `row` is a new row in the array
    val row = mutableListOf<Int>()

    repeat(4) { col -> // `col` is a new column in the row, ranges from 0 to 3
        row += col
    }

    // Append the row to the array, can also use the `add()` function
    list += row
}

// for each list in the list, print its element in matrix form
for(sublist in list) {
    for (j in sublist.indices){
        print("$j ")
    }

    println() // new line after each row
}

/*
You can also access particular elements like:
list[0][0] -> First element of the first row
or
list.get(0).get(0) -> Same as above
*/
Enter fullscreen mode Exit fullscreen mode

This code outputs the following:

0 1 2 3 
0 1 2 3 
0 1 2 3 
0 1 2 3
Enter fullscreen mode Exit fullscreen mode

And hence we can create dynamic lists in kotlin as per our needs.

N-Dimensional Arrays in Kotlin

Using the approaches discussed above, it wouldn't be hard to create 3D, 4D or even more dimensional arrays.

If the dataset you have is known, you can use the arrayOf() function, or to have variable array data, you can go ahead with mutableListOf() functions to create the arrays.

Conclusion

In this tutorial you learned about the arrays and mutable lists in kotlin using arrayOf() and mutableListOf() functions.

These functions help you to create arrays and lists of any data type in Kotlin, to store values and perform actions based on that data.

I hope you find this tutorial useful. Share it with your friends who are beginning with kotlin!

Oldest comments (0)