/
Iterators.kt
46 lines (39 loc) · 1.67 KB
/
Iterators.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
/**
* Creates an [Iterator] for an [java.util.Enumeration], allowing to use it in `for` loops.
* @sample samples.collections.Iterators.iteratorForEnumeration
*/
@kotlin.jvm.JvmVersion
public operator fun <T> java.util.Enumeration<T>.iterator(): Iterator<T> = object : Iterator<T> {
override fun hasNext(): Boolean = hasMoreElements()
public override fun next(): T = nextElement()
}
/**
* Returns the given iterator itself. This allows to use an instance of iterator in a `for` loop.
* @sample samples.collections.Iterators.iterator
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> Iterator<T>.iterator(): Iterator<T> = this
/**
* Returns an [Iterator] wrapping each value produced by this [Iterator] with the [IndexedValue],
* containing value and it's index.
* @sample samples.collections.Iterators.withIndexIterator
*/
public fun <T> Iterator<T>.withIndex(): Iterator<IndexedValue<T>> = IndexingIterator(this)
/**
* Performs the given [operation] on each element of this [Iterator].
* @sample samples.collections.Iterators.forEachIterator
*/
public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit) : Unit {
for (element in this) operation(element)
}
/**
* Iterator transforming original `iterator` into iterator of [IndexedValue], counting index from zero.
*/
internal class IndexingIterator<out T>(private val iterator: Iterator<T>) : Iterator<IndexedValue<T>> {
private var index = 0
final override fun hasNext(): Boolean = iterator.hasNext()
final override fun next(): IndexedValue<T> = IndexedValue(index++, iterator.next())
}