有没有办法编写下面的 Kotlin 代码,以便它在 JVM 和 JavaScript 上以相同的方式编译和工作?
fun <A: Any> request(request: Any): A = runBlocking {
suspendCoroutine<A> { cont ->
val subscriber = { response: A ->
cont.resume(response)
}
sendAsync(request, subscriber)
}
}
fun <Q : Any, A : Any> sendAsync(request: Q, handler: (A) -> Unit) {
// request is sent to a remote service,
// when the result is available it is passed to handler(... /* result */)
}
当编译为针对 JVM 时,代码可以编译并正常工作。由于函数 runBlocking 不存在,以 JavaScript 为目标时会发出编译错误