Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "lambda@" mean in Kotlin

Tags:

kotlin

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@".

like image 561
Sheed Avatar asked May 31 '26 17:05

Sheed


1 Answers

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

like image 145
SpencerPark Avatar answered Jun 03 '26 16:06

SpencerPark