https://kotlinlang.org logo
#stdlib
Title
# stdlib
r

Rob Elliot

01/30/2022, 3:00 PM
Candidate mirror function to
fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>>
to include in the stdlib:
fun <T> Iterable<IndexedValue<T>>.withoutIndex(): List<T> = map(IndexedValue<T>::value)
e

ephemient

01/30/2022, 6:27 PM
withIndex provides a indexed view, not a copy, while map copies eagerly
r

Rob Elliot

01/30/2022, 6:53 PM
I'm sure there's a better implementation, it's the concept I'm suggesting. Perhaps I should just have gone with the signature:
fun <T> Iterable<IndexedValue<T>>.withoutIndex(): Iterable<T>
d

Dominaezzz

01/30/2022, 8:03 PM
Feels a bit specific. Like what if the indexes are wrong.
r

Rob Elliot

01/30/2022, 8:11 PM
What if they are? It's just to discard them. Iteration order would be unchanged.
m

marcinmoskala

02/02/2022, 9:53 PM
Copy code
fun <T> Iterable<IndexedValue<T>>.withoutIndex(): Iterable<T> = UnindexedIterable(this)

internal class UnindexedIterable<T>(private val iterable: Iterable<IndexedValue<T>>) : Iterable<T> {
    override fun iterator(): Iterator<T> = UnindexedIterator(iterable.iterator())
}

internal class UnindexedIterator<out T>(private val iterator: Iterator<IndexedValue<T>>) : Iterator<T> {
    override fun hasNext(): Boolean = iterator.hasNext()
    override fun next(): T = iterator.next().value
}
2 Views