Added stdlib function withIndices() converting sequence (Iterable) to sequence of index-value pairs.

#KT-1195 fixed
This commit is contained in:
Evgeny Gerashchenko
2012-02-27 17:43:04 +04:00
parent 12f7d463ad
commit 4c70d341b1
2 changed files with 48 additions and 1 deletions
+37 -1
View File
@@ -1,9 +1,10 @@
package std.util
// Number of extension function for ava.lang.Iterable that shouldn't participate in auto generation
// Number of extension function for java.lang.Iterable that shouldn't participate in auto generation
import java.util.Collection
import java.util.List
import java.util.AbstractList
import java.util.Iterator
/**
* Count the number of elements in collection.
@@ -83,3 +84,38 @@ fun <T> java.lang.Iterable<T>.contains(item : T) : Boolean {
return false
}
/**
* Convert collection of arbitrary elements to collection of
*/
fun <T> java.lang.Iterable<T>.withIndices() : java.lang.Iterable<#(Int, T)> {
return object : java.lang.Iterable<#(Int, T)> {
override fun iterator(): java.util.Iterator<#(Int, T)> {
// TODO explicit typecast as a workaround for KT-1457, should be removed when it is fixed
return NumberedIterator<T>(this@withIndices.iterator().sure()) as java.util.Iterator<#(Int, T)>
}
}
}
private class NumberedIterator<TT>(private val sourceIterator : java.util.Iterator<TT>) : java.util.Iterator<#(Int, TT)> {
private var nextIndex = 0
override fun remove() {
try {
sourceIterator.remove()
nextIndex--;
} catch (e : UnsupportedOperationException) {
throw e
}
}
override fun hasNext(): Boolean {
return sourceIterator.hasNext();
}
override fun next(): #(Int, TT) {
val result = #(nextIndex, sourceIterator.next())
nextIndex++
return result
}
}
+11
View File
@@ -27,4 +27,15 @@ class ListTest() : TestSupport() {
val t = data.last
assertEquals("bar", t)
}
fun testWithIndices() {
val withIndices = data.withIndices()
var index = 0
for (withIndex in withIndices) {
assertEquals(withIndex._1, index)
assertEquals(withIndex._2, data[index])
index++
}
assertEquals(data.size(), index)
}
}