在lambda中使用return?

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

mainRepo.fetchUpcomingTrips { trips -> if (trips.isEmpty()) { showEmptyViews() return } // run some code if it's not empty } 

有没有办法像那样回报?

我知道我可以把它放在一个if else块中,但是如果有其他情况,我讨厌写作,当我有更多的条件时,在我看来这是不太可理解的。

只需使用限定的返回语法: return@fetchUpcomingTrips

在Kotlin中,在lambdaexpression式中返回意味着从最内层的嵌套fun (忽略lambdaexpression式)返回,并且在未被内联的 lambdaexpression式中不允许。

return@label语法用于指定从中返回的范围。 你可以使用lambda函数的名字( fetchUpcomingTrips )作为标签:

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

有关:

  • 返回语言参考中的标签

  • 什么“返回@”是什么意思?

简单的return表明你从函数返回。 既然你不能从lambda函数中返回,编译器会报错。 相反,你想从lambda返回,你必须使用一个标签:

  mainRepo.fetchUpcomingTrips { trips -> if (trips.isEmpty()) { showEmptyViews() return@fetchUpcomingTrips } //run some code if it's not empty } 

回报允许我们从外部函数返回。 最重要的用例是从lambdaexpression式返回

匿名函数中的return语句将从匿名函数本身返回。

 fun foo() { ints.forEach(fun(value: Int) { if (value == 0) return // local return to the caller of the anonymous fun, ie the forEach loop print(value) }) } 

当返回一个值时,解析器会优先考虑合格的返回值,即

 return@a 1 

的意思是“在标签@a处返回1”而不是“返回标记的expression式(@a 1)”。 返回默认从最近的封闭函数或匿名函数返回。

中断终止最近的封闭循环。

继续进行到最近的封闭循环的下一步。

更多详情请参阅退货和跳转,中断和继续标签

return的替代可能是

 mainRepo.fetchUpcomingTrips { trips -> if (trips.isEmpty()) showEmptyViews() else { //run some code if it's not empty } }