Kotlin中如何从构造函数内的匿名挂起函数中调用类成员方法
解决方案
核心思路
你当前遇到的问题本质是传入构造函数的是无接收者的挂起函数类型,无法直接访问BasicContinuation的成员方法。最简单的方案是将构造函数的入参改为带BasicContinuation接收者的挂起函数类型,利用Kotlin原生的接收者函数特性实现成员访问,不需要额外的匿名内部类、自定义test方法或者set方法。
修改代码示例
调整BasicContinuation构造函数
仅需要修改构造函数的入参类型和协程创建逻辑,其余代码完全不需要改动:
class BasicContinuation : Continuation<Unit> { var coroutine: Continuation<Unit> override val context: CoroutineContext = EmptyCoroutineContext private var nextStep: SuspendableStep? = null // 仅修改构造函数的入参类型,改为带接收者的挂起函数 constructor(task: suspend BasicContinuation.() -> Unit) { // 创建协程时传入当前实例作为接收者 coroutine = task.createCoroutine(receiver = this, completion = this) } override fun resumeWith(result: Result<Unit>) { nextStep = null result.exceptionOrNull()?.let { e -> Logger.handle("Error with plugin!", e) } } suspend fun wait(cycles: Int): Unit = suspendCoroutine { check(cycles > 0) { "Wait cycles must be greater than 0." } nextStep = SuspendableStep(WaitCondition(cycles), it) } }
调整后的调用方式
直接在构造函数的lambda内调用成员方法即可,还可以用Kotlin的尾随lambda语法简化写法:
fun main() { BasicContinuation { println("HELLO") wait(1) println("WORLD") }.coroutine.resume(Unit) }
该方案没有新增任何额外的接口、方法或者样板代码,是Kotlin下这类场景的标准实现方式。
内容的提问来源于stack exchange,提问作者clem585
相关产品推荐
相关产品推荐

