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

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

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

Is there a way to return like that?

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.

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.

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 
    }

    // ...
}

Related:

Kotlin相关问答推荐

Scala性状线性化等价于Kotlin

Rabin-Karp字符串匹配的实现(Rolling hash)

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

将 Integer 转换为 Unit 编译成功

如何缩短 MaterialTheme.colors.primary?

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

如何在 Kotlin 中不受约束?

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

为什么没有remember 的 mutableStateOf 有时会起作用?

Kotlin 中多个 init 块的用例?

在 kotlin 中写入 parcer 可空值

Kotlin 语言是如何用 Kotlin 编写的?

Kotlin:如何在活页夹中返回正在运行的服务实例?

使用kotlinx协同程序测试中的类时出错

使用导航组件在不同的图形之间导航

指定为非null的参数在ArrayAdaper中为null

Kotlin out-projected 类型禁止使用

Recyclerview: listen to padding click events

项目不会使用 Kotlin 1.1.3 构建

Kotlin:如何使用扩展函数扩展枚举类