从那里:https://kotlinlang.org/docs/reference/this-expressions.html#qualified
我们有这样的代码:
val funLit = lambda@ fun String.() {}
跑到那里https://pl.kotl.in/Syah1jaIN它编译和调用没有错误
我认为“lambda@”是一个注解,但这里的文档: https://kotlinlang.org/docs/reference/annotations.html 指的是类似“@word”的语法,而不是“word@”。
最佳答案
它确实是一个标签,并且在该示例中特别有用,因为它标记了一个匿名函数。您将标签用于限定引用(如 this
)。
在下面的示例中,lambda 定义了一个内部方法 nested
,它可能想要从 funLit
访问 this
。由于它是匿名的,我们需要对其进行标记,lambda
是一个任意标识符。
fun main() {
val funLit = lambda@ fun String.() {
println("this: " + this)
println("this@lambda: " + this@lambda)
fun String.nested() {
println("this in String.nested(): " + this)
println("this@nested in String.nested(): " + this@nested)
println("this@lambda in String.nested(): " + this@lambda)
}
"nested".nested()
}
"funLit".funLit()
}
运行它可以非常清楚地显示 this
是用限定符引用的。
this: funLit
this@lambda: funLit
this in String.nested(): nested
this@nested in String.nested(): nested
this@lambda in String.nested(): funLit
这是一个 Playground 链接:https://pl.kotl.in/SJrlUs6LE
关于kotlin - "lambda@"在 Kotlin 中是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030860/