Kotlin:"return @"是什么意思?意思是?
我在我的一个项目中使用RxJava,我使用Android Studio插件将我的一个类转换为Kotlin,并在map flatMap
lambda(java中的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)
})
In Kotlin, the return@label
syntax is used for specifying which function among several nested ones this statement returns from.
它与函数文字(lambda)和局部函数一起使用.未标记的return
语句从封闭的fun
的最近(即最里面)返回(忽略lambda).考虑一下此功能:
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"]
非本地退货(即从外部函数)仅支持 local 和内联函数,因为如果未内联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
.