Kotlin:什么是“return@"?意思是? [英] Kotlin: Whats does "return@" mean?
问题描述
我在我的一个项目中使用 RxJava,我使用 Android Studio 插件和 map flatMap
lambda(java 中的 Func1)之一将我的一个类转换为 Kotlin,中间体返回外观像下面的@Func1
.
I'm using RxJava in one of my projects, I converted one of my classes to Kotlin using the Android Studio plugin and in one of map flatMap
lambda (Func1 in java), intermediates returns looks like the following @Func1
.
我不知道这是什么意思.
I have no idea what this means.
something.flatMap(Func1<ArticleCriteria, Observable<Pair<String, String>>> {
val isTemporaryClone = it.isATemporaryClone
val isTheOriginalToken = it.tokenIsOriginalHere
if (isTemporaryClone) {
if (!isTheOriginalToken) {
return@Func1 paramsError("Token is always original for temp articles")
}
return@Func1 mJobRunner.doNotRun(DeleteArticleJob.TAG)
.doOnNext(deletePersonalActionById(articleId))
}
runArticleJobAsync(DeleteArticleJob.TAG, it)
})
推荐答案
在 Kotlin 中,return@label
语法用于指定该语句返回的嵌套函数中的哪个函数.
In Kotlin, the return@label
syntax is used for specifying which function among several nested ones this statement returns from.
它适用于函数字面量 (lambdas) 和局部函数.未标记的 return
语句从最近的(即最里面的)封闭的 fun
(忽略 lambdas)返回.考虑这个函数:
It works with function literals (lambdas) and local functions. Non-labeled return
statements return from the nearest (i.e. innermost) enclosing fun
(ignoring lambdas). Consider this function:
fun foo(ints: List<Int>) {
ints.forEach {
if (it == 0) return
print(it)
}
}
这里,return
将完成 foo
的执行,而不仅仅是 lambda.
Here, return
will finish the execution of foo
, not just the lambda.
但是如果您想从任何其他函数(一个 lambda 或外部 fun
)返回,您必须在 return
语句中将其指定为标签:
But if you want to return from any other function (a lambda or an outer fun
) you have to specify it as a label at return
statement:
fun foo(ints: List<Int>) {
ints.forEach {
if (it == 0) return@forEach // implicit label for lambda passed to forEach
print(it)
}
}
fun foo(ints: List<Int>): List<String> {
val result = ints.map f@{
if (it == 0) return@f "zero" // return at named label
if (it == -1) return emptyList() // return at foo
"number $it" // expression returned from lambda
}
return result
}
foo(listOf(1, -1, 1)) // []
foo(listOf(1, 0, 1)) // ["number 1", "zero", "number 1"]
非本地返回(即从来自 lambda 的外部函数)仅支持 local 和 inline 函数,因为如果 lambda 没有内联(或者函数被放置在对象内), 并不能保证只在封闭函数内部调用(例如它可以存储在变量中并稍后调用),并且在这种情况下非局部返回没有意义.
Non-local return (i.e. return from outer functions) from a lambda is only supported for local and inline functions, because if a lambda is not inlined (or a function is placed inside an object), it is not guaranteed to be called only inside the enclosing function (e.g. it can be stored in a variable and called later), and the non-local return would make no sense in this case.
对于限定的this
,用于引用外部作用域的接收者:this@outer
.
这篇关于Kotlin:什么是“return@"?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!