且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 lambda 中使用 return ?

更新时间:2023-11-11 13:02:34

只需使用限定的返回语法: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@"是什么意思?