In this tutorial, you shall learn how to create an array or arrays in Kotlin, and how to access the elements of inner array using a loop statement, with examples.

Kotlin Array or Arrays

An Array of Arrays is a scenario where the elements of outer array are array of elements.

Syntax

The syntax to create an array of arrays arrs is

val arrs = arrayOf(
    arrayOf(/*elements*/),
    arrayOf(/*elements*/),
    arrayOf(/*elements*/),
)
ADVERTISEMENT

Examples

1. Create array of arrays and iterate over the elements using For loop

In the following program, we create an array of arrays, and then traverse through the elements of this array using nested For loop.

Refer Kotlin For Loop tutorial.

Main.kt

fun main(args: Array<String>) {
    val arrs = arrayOf(
        arrayOf("a", "b", "c"),
        arrayOf("A", "B", "C"),
        arrayOf("@", "#", "$"),
    )
    for (arr in arrs) {
        for (element in arr) {
            print("$element  ")
        }
        println()
    }
}

Output

a  b  c  
A  B  C  
@  #  $

2. Access elements in array of arrays using index notation

We can also use array[index][index] notation to access the elements of inner arrays.

Main.kt

fun main(args: Array<String>) {
    val arrs = arrayOf(
        arrayOf("a", "b", "c"),
        arrayOf("A", "B", "C"),
        arrayOf("@", "#", "$"),
    )
    val x = arrs[1][2]
    println(x)
}

Output

C

Conclusion

In this Kotlin Tutorial, we learned how to create an Array of Arrays, and how to traverse through the inner arrays and their elements, in Kotlin programming language with examples.