在 lambda 中使用 return ? [英] Using return inside a lambda?
问题描述
在下面的代码中,如果trips为空,我想显示我的空视图然后返回并避免运行下面的代码,但编译器说这里不允许返回".
In the code below, I want to show my empty views if trips is empty and then return and avoid running the below code, but the compiler says "return is not allowed here".
mainRepo.fetchUpcomingTrips { trips ->
if (trips.isEmpty()) {
showEmptyViews()
return
}
// run some code if it's not empty
}
有没有办法像这样返回?
Is there a way to return like that?
我知道我可以把它放在 if else 块中,但我讨厌写 if else 的,在我看来,当有更多条件时,它不太容易理解/可读.
I know I can just put it in an if else block but I hate writing if else's, it's less understandable/readable in my opinion when there's a few more conditions.
推荐答案
只需使用限定的返回语法:return@fetchUpcomingTrips
.
Just use the qualified return syntax: return@fetchUpcomingTrips
.
在 Kotlin 中,lambda 中的 return
表示从最内层嵌套的 fun
返回(忽略 lambdas),并且不允许在不是 内联.
In Kotlin, return
inside a lambda means return from the innermost nesting fun
(ignoring lambdas), and it is not allowed in lambdas that are not inlined.
return@label
语法用于指定返回的范围.您可以使用 lambda 传递给的函数名称 (fetchUpcomingTrips
) 作为标签:
The return@label
syntax is used to specify the scope to return from. You can use the name of the function the lambda is passed to (fetchUpcomingTrips
) as the label:
mainRepo.fetchUpcomingTrips { trips ->
if (trips.isEmpty()) {
showEmptyViews()
return@fetchUpcomingTrips
}
// ...
}
相关:
在标签处返回 在语言参考中
Return at labels in the language reference
这篇关于在 lambda 中使用 return ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!