
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
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