gpt4 book ai didi

Kotlin:tailrec 让暂停的乐趣永无止境

转载 作者:行者123 更新时间:2023-12-02 12:02:39 31 4
gpt4 key购买 nike

我正在学习如何使用 CompletableFuture 使协程与 Java 库一起工作。下面是我的代码:

// x invokes y invokes z invokes Java client
suspend fun x(i: Int, client: FakeJavaClient): Int {

fun z(k: Int): Int {
println("z: $k")
return client.query(k).get()
}

tailrec // with 'tailrec', the code never terminates
suspend fun y(j: Int): Int {
val ret = z(j)
if (ret > 10) {
return ret
}

return y(j + 1)
}

return y(i)
}

fun main() {
runBlocking {
launch(Dispatchers.IO) {
FakeJavaClient().use { x(0, it) }
}
}
println("Done")
}

class FakeJavaClient : AutoCloseable {
private val executor = Executors.newFixedThreadPool(10)

fun query(i: Int): CompletableFuture<Int> {
val f = CompletableFuture<Int>()
executor.submit {
Thread.sleep(1000)
f.complete(i * 2)
}
return f
}

override fun close() {
executor.shutdown()
executor.awaitTermination(10, TimeUnit.SECONDS)
}
}

如果我添加 tailrec功能修饰符 y ,代码输出如下,永不结束:
z: 0
z: 0
z: 0
z: 0
z: 0
...

如果我删除 tailrecy ,代码的行为符合我的期望
z: 0
z: 1
z: 2
z: 3
z: 4
z: 5
z: 6
Done

有人可以帮助我了解这里发生了什么吗?

最佳答案

这看起来像是一个已知问题:Wrong code generated for a local tailrec suspend function .

关于Kotlin:tailrec 让暂停的乐趣永无止境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60647842/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com