美文网首页
Kotlin挂起函数suspend

Kotlin挂起函数suspend

作者: 雨来 | 来源:发表于2021-06-21 16:38 被阅读0次

要记着的准则

挂起函数只能用到协程和挂起函数中

挂起函数 如果有返回值(则是最后一行是返回值)

fun main() = runBlocking {
    
    launch {
        println(returnEndLine())
    }
    //这个会先执行 如果是在main方法中这一句的话则一定会 runBlocking语句执行完才会执行main方法中的
    println("协程执行完再能执行到这里")
}
suspend fun returnEndLine(): Int {
    return try {
        1 / 0
    } catch (execption: Exception) {
        2
    }finally {
        println("end")
    }

}
//try catch finally 当然也是可以赋值给一个变量的
suspend fun test():Int{

    val result = try {
        1 / 0
    } catch (execption: Exception) {
        2
    }finally {
        println("end")
    }
    
    return result
}

相关文章

网友评论

      本文标题:Kotlin挂起函数suspend

      本文链接:https://www.haomeiwen.com/subject/ociyyltx.html