added a helper method for converting functions into iterators (which have all the various standard library APIs on them)

This commit is contained in:
James Strachan
2012-03-25 08:10:17 +01:00
parent 85bf6dc5a7
commit a194764657
3 changed files with 43 additions and 0 deletions
+6
View File
@@ -1,6 +1,7 @@
package kotlin
import kotlin.support.AbstractIterator
import kotlin.support.FunctionIterator
import java.util.*
import java.util.Iterator
@@ -77,3 +78,8 @@ inline fun <T, R> java.util.Iterator<T>.flatMap(transform: (T)-> java.util.Itera
return flatMapTo<>(ArrayList<R>(), transform)
}
*/
/**
* Returns an iterator which invokes the function to calculate the next value on each iteration until the function returns null
*/
inline fun <T> iterate(nextFunction: () -> T?) : Iterator<T> = FunctionIterator(nextFunction)
@@ -70,4 +70,19 @@ abstract class AbstractIterator<T>: java.util.Iterator<T> {
protected fun done() {
state = State.Done
}
}
/**
* An [[Iterator]] implementation which invokes a function to calculate the next value in the iteration
* until the function returns null
*/
class FunctionIterator<T>(val nextFn: () -> T?) : AbstractIterator<T>() {
override fun computeNext(): T? {
val next = (nextFn)()
if (next == null) {
done()
}
return next
}
}