fun main(args: Array) { val f = create { println(1) yield() // 1 println(2) yield() // 2 println(3) } f.resume() // starts "f" f.resume() // continues from "yield 1" f.resume() // continues from "yield 2" f.resume() // continues from "yield 2" (again) } class YieldingFunction { private var c: Continuation? = null fun resume() { c?.resume(Unit) } suspend fun yield() { suspendCoroutineOrReturn { it: Continuation -> c = it COROUTINE_SUSPENDED } } companion object { fun create(block: suspend YieldingFunction.() -> Unit): YieldingFunction { val continuation = MyContinuation() return YieldingFunction().apply { c = block.createCoroutineUnchecked(this, continuation) } } } } class MyContinuation: Continuation { override val context: CoroutineContext = EmptyCoroutineContext override fun resume(value: Unit) {} override fun resumeWithException(exception: Throwable) = throw exception }