我的代码类似于下面的代码。
suspend fun foo() {
withContext(Dispatchers.IO) {
// how to return at foo?
}
// more code here
}如何在foo退货?当我只做普通的老式return时,我得到了'return' is not allowed here和return@withContext的建议,但我不想调用withContext上的return,我想调用foo上的return。
发布于 2021-02-21 04:02:39
suspend fun foo() {
return withContext(Dispatchers.IO) {
return@withContext something
}
}发布于 2021-02-21 04:40:27
您不能从withContext内部调用return@foo,所以您唯一的选择是从withContext返回一些值,然后检查它,然后决定是继续还是返回。
例如:
suspend fun foo() {
withContext(Dispatchers.IO) {
// Code that might return null or not
}?.let {
// More code here
}
}发布于 2021-02-21 11:45:11
我猜您想要做的是,根据withContext代码块中的某个分支代码,有条件地提前从foo()返回。
因为withContext不是内联函数,所以它只能从自身返回。所以你可以这样做:
suspend fun foo() {
var shouldContinue = true
withContext(Dispatchers.IO) {
//some code
if (something) { // condition under which you want to return early
shouldContinue = false
return@withContext
}
// some more code
}
if (!shouldContinue) {
return
}
// more code here
}或者让您的withContext从它的所有分支返回一个布尔值,以确定是否继续:
suspend fun foo() {
val shouldContinue = withContext(Dispatchers.IO) {
//some code
if (something) { // condition under which you want to return early
return@withContext false
}
// some more code
true // implicit return
}
if (!shouldContinue) {
return
}
// more code here
}或者,如果你使用它来产生一些你要做的事情的结果,那么对于它可以提前退出而不返回任何东西的情况,你可以返回null:
suspend fun foo() {
val result = withContext(Dispatchers.IO) {
//some code
if (something) { // condition under which you want to return early
return@withContext null
}
// some more code
yourResult
}
result ?: return // no result, return early
// do something with non-null result
}https://stackoverflow.com/questions/66295703
复制相似问题