如你所说,
coroutines
是标准的功能。
你必须使用
suspend
关键字,如果函数将被挂起,例如IO,或者如果调用另一个函数
暂停
功能,例如
delay
.
错误处理可以用
try-catch
语句。
import kotlinx.coroutines.delay
import java.lang.Exception
import kotlin.math.ceil
const val SLEEP_INTERVAL_IN_MILLISECONDS = 200
suspend fun alpha(number: Int): Int {
delay(SLEEP_INTERVAL_IN_MILLISECONDS)
return number + 1
}
suspend fun bravo(number: Int): Int {
delay(SLEEP_INTERVAL_IN_MILLISECONDS)
return ceil(1000 * Math.random() + number).toInt()
}
fun charlie(number: Int): Int =
number.takeIf { it % 2 == 0 } ?: throw IllegalStateException(number.toString())
suspend fun run() {
try {
val result = charlie(bravo(alpha(42)))
println(result)
} catch (e: Exception) {
println(e)
}
}
suspend fun main() {
run()
}
如果您喜欢更实用的错误处理样式,可以执行以下操作:
suspend fun run() {
runCatching { charlie(bravo(alpha(42))) }
.onFailure { println(it) }
.onSuccess { println(it) }
}