【发布时间】:2020-06-28 02:25:17
【问题描述】:
我正在学习 Kotlin 的协程。
代码 A 来自文章https://kotlinlang.org/docs/reference/coroutines/flow.html
yield(i) 在 Kotlin 中是什么意思?
代码 A
fun foo(): Sequence<Int> = sequence { // sequence builder
for (i in 1..3) {
Thread.sleep(100) // pretend we are computing it
yield(i) // yield next value
}
}
fun main() {
foo().forEach { value -> println(value) }
}
【问题讨论】:
-
如果你知道任何 Python,
yield(i)与 Python 生成器函数的yield i非常相似。但在 Kotlin 中,它不是语言功能,它只是suspend fun。