使用kotlin协程实现Generator并支持传入初始参数
package leo.demo
import kotlin.coroutines.*
/**
* 序列接口
*/
interface Generator<T> {
operator fun iterator(): Iterator<T>
}
/**
* 序列实现类
*/
class GeneratorImpl<T>
(private val block: suspend GeneratorScope<T>.(T) -> Unit, private val parameter: T) :
Generator<T> {
override fun iterator(): Iterator<T> {
return GeneratorIterator(block, parameter)
}
}
/**
* 序列状态机,表示是否准备好下一个值
*/
sealed class State {
class NotReady(val continuation: Continuation<Unit>) : State()
class Ready<T>(val continuation: Continuation<Unit>, val nextValue: T) : State()
object Done : State