Kotlin array traversal example

In this Kotlin example, we will discuss four different ways to loop over an Array in Kotlin.
All Kotlin examples at All Kotlin Examples.

Kotlin array traversal example

The example loops over an array using four different ways of traversal.
fun main() {

    val nums = arrayOf(1, 2, 3, 4, 5, 6, 7)

    nums.forEach({ e -> print("$e ") })

    println()

    nums.forEachIndexed({i, e -> println("nums[$i] = $e")})

    for (e in nums) {
        print("$e ")
    }

    println()

    val it: Iterator<Int> = nums.iterator()

    while (it.hasNext()) {
        
        val e = it.next()
        print("$e ")
    }
}
Output:
1 2 3 4 5 6 7 
nums[0] = 1
nums[1] = 2
nums[2] = 3
nums[3] = 4
nums[4] = 5
nums[5] = 6
nums[6] = 7
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 
All Kotlin examples at All Kotlin Examples.


Comments