From there: https://kotlinlang.org/docs/reference/this-expressions.html#qualified
we have a code like so:
val funLit = lambda@ fun String.() {}
Run there https://pl.kotl.in/Syah1jaIN it compiles and is called without error
I thought "lambda@" was an annotation but the documentation here: https://kotlinlang.org/docs/reference/annotations.html refers to a syntax sorta like "@word", not "word@".
It is indeed a label and is especially useful in that example as it labels an anonymous function. You use the label for qualifying references (like this).
In the following example the lambda defines an inner method nested which may want to access the this from the funLit. Since it is anonymous we need to label it, lambda is an arbitrary identifier.
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()
}
Running it shows very clearly what this is being referred to with the qualifier.
this: funLit
this@lambda: funLit
this in String.nested(): nested
this@nested in String.nested(): nested
this@lambda in String.nested(): funLit
Here is a playground link: https://pl.kotl.in/SJrlUs6LE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With