lambda - 在 lambda 中使用 return?

在下面的代码中,如果trips为空,我想显示我的空 View ,然后返回并避免运行下面的代码,但是编译器说“这里不允许返回”。

mainRepo.fetchUpcomingTrips { trips ->
    if (trips.isEmpty()) {
        showEmptyViews()
        return
    }

    // run some code if it's not empty
}

有没有办法这样返回?

我知道我可以把它放在 if else block 中,但我讨厌写 if else 的,在我看来,当有更多条件时,它不太容易理解/可读。

最佳答案

只需使用合格的返回语法:return@fetchUpcomingTrips

在 Kotlin 中,lambda 中的 return 表示从最内层的嵌套 fun 返回(忽略 lambda),并且在不是 inlined 的 lambda 中是不允许的.

return@label 语法用于指定返回的范围。您可以使用 lambda 传递给的函数的名称 (fetchUpcomingTrips) 作为标签:

mainRepo.fetchUpcomingTrips { trips ->
    if (trips.isEmpty()) {
        showEmptyViews()
        return@fetchUpcomingTrips 
    }

    // ...
}

相关:

  • Return at labels在语言引用中

  • Whats does “return@” mean?

https://stackoverflow.com/questions/45348820/

相关文章:

android - 在 Kotlin 中使用 Gson 解析 JSON 数组

android - 使用 Kotlin for Android 进行数据绑定(bind)的问题

types - Kotlin:从列表(或其他功能转换)中消除空值

android - 缺少主调度程序的模块

android - 如何在 androidTest 范围内使用 kapt

kotlin - 如何从包类名称字符串中获取 Kotlin KClass?

android - 在 Android Studio 中创建 Kotlin 库

java - 在 Kotlin 中,如何转换 Int?到一个 Int

android - 错误 : supertypes of the following classes

kotlin - Delegates.notNull 和 lateinit Kotlin 的区别