https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

anlex N

03/27/2024, 11:54 AM
https://kotlinlang.org/docs/inline-functions.html If I use
crossinline
, I only can use variables in the
f
body, right? or how to better understand
crossinline
? what is non-local returns?
g

gildor

03/27/2024, 12:06 PM
This section of the doc has explanation of non-local return
Not sure that I understand question about variables In function f Crossiline means that lambda body will not be inlined, even thought it's a part of inline function, because it used by some context where it's not possible (like in example of the code, where it's called in a body of another anonymous class) As result, crossiline lambda have other limitations of non-inline functions, because they are not a part of body of the function, and cannot return from it
a

anlex N

03/27/2024, 12:18 PM
fun f
and
val f
, Why use it this way?so crazy, oh my god.
g

gildor

03/27/2024, 12:19 PM
Be free to edit page, it's indeed unnecessary confusing No need to over react
My answer still stands, there is no limitation on usage of anything inside of Runnable implementation except what is usually limited for normal methods or classes, like return from parent context
a

anlex N

03/27/2024, 12:25 PM
the enclosing function mean
foo
or
ordinaryFunction
?
m

Miroljub Enjaković [EpicGuy4000]

03/27/2024, 12:29 PM
enclosing function in this context means
foo
Copy code
fun foo() {
    ordinaryFunction {
        return@foo // ERROR: cannot make `foo` return here
    }
}

fun foo() {
    ordinaryFunction {
        return@ordinaryFunction // Success
    }
}
Here is a labeled version of that code
a

anlex N

03/27/2024, 12:56 PM
based on your words,
body
can not use
return
, label syntax, and exit
f
, right?
m

Miroljub Enjaković [EpicGuy4000]

03/27/2024, 1:37 PM
In the words of the documentation, body can only use labeled return for the local lambda
Copy code
fun foo() {
    f {
        println("foo.f.body")
        return@f
    }
}

inline fun f(crossinline body: () -> Unit) {
    val f = object: Runnable {
        override fun run() = body()
    }
    f.run()
}

fun main() {
    foo()
}