All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlin.collections.Iterators.kt Maven / Gradle / Ivy

There is a newer version: 1.0.7
Show newest version
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")

package kotlin

import java.util.Enumeration

/**
 * Creates an [Iterator] for an [Enumeration], allowing to use it in `for` loops.
 */
public operator fun  Enumeration.iterator(): Iterator = object : Iterator {
    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.
 */
public operator fun  Iterator.iterator(): Iterator = this

/**
 * Performs the given [operation] on each element of this [Iterator].
 */
public inline fun  Iterator.forEach(operation: (T) -> Unit) : Unit {
    for (element in this) operation(element)
}

/**
 * Data class representing a value from a collection or sequence, along with its index in that collection or sequence.
 *
 * @property value the underlying value.
 * @property index the index of the value in the collection or sequence.
 */
public data class IndexedValue(public val index: Int, public val value: T)

/**
 * A wrapper over another [Iterable] (or any other object that can produce an [Iterator]) that returns
 * an indexing iterator.
 */
public class IndexingIterable(private val iteratorFactory: () -> Iterator) : Iterable> {
    override fun iterator(): Iterator> = IndexingIterator(iteratorFactory())
}

/**
 * Iterator transforming original `iterator` into iterator of [IndexedValue], counting index from zero.
 */
public class IndexingIterator(private val iterator: Iterator) : Iterator> {
    private var index = 0
    final override fun hasNext(): Boolean = iterator.hasNext()
    final override fun next(): IndexedValue = IndexedValue(index++, iterator.next())
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy