在lambda中使用return吗? [英] Using return inside a lambda?

查看:74
本文介绍了在lambda中使用return吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果行程为空,我想显示我的空视图,然后返回并避免运行下面的代码,但是编译器说此处不允许返回".

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返回(忽略lambda),并且在非

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

"return @"是什么意思?

这篇关于在lambda中使用return吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆