added a helper method for converting functions into iterators (which have all the various standard library APIs on them)
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user