Kotlin Array - iterator() Function



The Kotlin array iterator() function is used to create an iterator for iterating over the elements of an array.

An iterator provides sequential access to the element of a collection or another entity such as an array.

Syntax

Following is the syntax of Kotlin array iterator() function −

operator fun iterator(): Iterator<T>

Parameters

This function does not accepts any parameter.

Return value

This function returns an iterator objects.

Example 1

Following is the basic example to demonstrate the use of iterator() function −

fun main(args: Array<String>) {
   var array = Array(5) { i -> i}

   var iterator = array.iterator()

   println("The elements in the array are:")
   while(iterator.hasNext()){
      println(iterator.next())
   }      
}

Output

Following is the output −

The elements in the array are:
0
1
2
3
4

Example 2

Now, let's see another example. Here, we create an array that stores different types of element. We then use the iterator() function to iterate over the element −

fun main(args: Array<String>) {
   var array = Array(10) { i ->
      if(i<3) {'c'}
      else if(i<5) {"Hi"}
      else {5}
   }
   
   var iterator = array.iterator()
   
   println("The elements in the array are:")
   iterator.forEach() { x ->
      println(x)
   }
}

Output

Following is the output −

The elements in the array are:
c
c
c
Hi
Hi
5
5
5
5
5

Example 3

The example below creates an array of 10 integer and mutliplied each element of the array with two. We then use the iterator() function to traversing through the elements of the array −

fun main(args: Array<String>) {
   var array = Array(10) {
      it -> it*2
   }

   var iterator = array.iterator()
   var result=0
   
   for((index, value) in iterator.withIndex()) {
      result+=index*value
      print("$index*$value")
      if (index!=array.size-1)
         print(" + ")
      else
         print(" = ")
   }
   print(result)
}

Output

Following is the output −

0*0 + 1*2 + 2*4 + 3*6 + 4*8 + 5*10 + 6*12 + 7*14 + 8*16 + 9*18 = 570
kotlin_arrays.htm
Advertisements