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

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

问题描述

在下面的代码中,如果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

return@"是什么意思?

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

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