Kotlin Array.iterator()

Kotlin Array.iterator() Function

In Kotlin, the Array.iterator() function is used to obtain an iterator over the elements of an array. It provides a way to sequentially access the elements of the array using the iterator’s methods like next() and hasNext().

In this tutorial, we’ll explore the syntax of the Array.iterator() function, how to use it to iterate over array elements, and provide examples of its usage in Kotlin.

Syntax

The syntax of the iterator() function is as follows:

val iterator: Iterator<T> = array.iterator()

where

  • iterator – The iterator over the elements of the array.
  • array – The array for which to obtain an iterator.
  • T – The type of elements in the array.

Examples for Array.iterator() Function

1. Iterating Over an Integer Array

In this example, we’ll use the iterator() function to iterate over the elements of an array of integers using a while loop.

Kotlin Program

fun main() {
    val intArray = arrayOf(10, 20, 30, 40, 50)

    // Obtaining iterator for the integer array
    val iterator = intArray.iterator()

    // Iterating over the array using the iterator
    while (iterator.hasNext()) {
        val element = iterator.next()
        println("Element: $element")
    }
}

Output

Element: 10
Element: 20
Element: 30
Element: 40
Element: 50

2. Iterating Over a String Array

In this example, we’ll use the iterator() function to iterate over the elements of an array of strings using a for loop.

Kotlin Program

fun main() {
    val stringArray = arrayOf("apple", "banana", "orange", "grape")

    // Obtaining iterator for the string array
    val iterator = stringArray.iterator()

    // Iterating over the array using the iterator
    for (element in iterator) {
        println("Element: $element")
    }
}

Output

Element: apple
Element: banana
Element: orange
Element: grape

Summary

In this tutorial, we’ve covered the iterator() function in Kotlin arrays, its syntax, and how to use it to obtain an iterator for array elements. Whether you prefer using a while loop or a for loop, the iterator() function provides a convenient way to sequentially access elements in an array.