iterator所在位置是kotlin.collections.iterator,其相关用法介绍如下。

用法一

operator fun <T> Iterator<T>.iterator(): Iterator<T>

返回给定的迭代器本身。这允许在for 循环中使用迭代器的实例。

例子:

import java.util.*

fun main(args: Array<String>) {
//sampleStart
val mutableList = mutableListOf(1, 2, 3)
val mutableIterator = mutableList.iterator()

// iterator() extension is called here
for (e in mutableIterator) {
    if (e % 2 == 0) {
        // we can remove items from the iterator without getting ConcurrentModificationException
        // because it's the same iterator that is iterated with for loop
        mutableIterator.remove()
    }

    println("The element is $e")
}
//sampleEnd
}

输出:

The element is 1
The element is 2
The element is 3

用法二

operator fun <K, V> Map<out K, V>.iterator(): Iterator<Entry<K, V>>

Map 中的条目上返回 Iterator

例子:

import kotlin.test.*
import java.util.*

fun main(args: Array<String>) {
//sampleStart
val map = mapOf("beverage" to 2.7, "meal" to 12.4, "dessert" to 5.8)

for ((key, value) in map) {
    println("$key - $value") // prints: beverage - 2.7
                             // prints: meal - 12.4
                             // prints: dessert - 5.8
}
//sampleEnd
}

输出:

beverage - 2.7
meal - 12.4
dessert - 5.8

用法三

@JvmName("mutableIterator") operator fun <K, V> MutableMap<K, V>.iterator(): MutableIterator<MutableEntry<K, V>>

MutableMap 中的可变条目上返回 MutableIterator