Return@ From within function parameters / callback

If I have something like:

fun create( param1 : Int, param 2: (Int, String) -> Unit = {_,_ -> } ) : SomeDataClass {
    return SomeDataClass(params...).apply { init() }
}

fun myError(String) -> Unit //prints the error

fun caller() {
    //... outervariable : String?
    val x : SomeDataClass = create(1, { innerparam1, innerparam2 ->
        if(outervariable == null) return@create myError("My error")
        //do something, without return keyword
    })
}

There are a lot of things that are complicated to understand but the one I wonder is return@myFunction, I can assume it exits the function altogether even before it started (as “create” is supposed to be gathering its parameter list at this point), but then it also calls another line with the call to myError so Im just confused. Is there an official documentation page on this? google shows me the return@ docs aimed at lambdas which miss this case.

Hi, I’m not exactly sure what you mean to be honest. return@create returns from the lambda passed to create(), so yes, the docs you found are correct. If outervariable is null, it calls the myError and jumps out of the lambda.

according to the docs, return@label returns from the function/scope denoted by label, therefore return@create would not return from a lambda inside create, it would return from create itself and finish its execution before it started, or is the line 10 evaluated after the function started?

a function usually has setup code, where the parameters are placed in the registry/memory adresses for the function, and then the first line of the function body is executed. The docs do not show a case where the label is returned from the parameter list

What does it mean to return from a function before it started? If it didn’t started yet, there is nowhere to return from. What does it mean the “label is returned from the parameter list”?

In this code sample we call the create function passing a lambda to it. create invokes the lambda. return@create returns from the lambda back to create.

There are some syntax errors in the code, but I assume param 2 is actually init.

1 Like