Home > Software engineering >  Returns and qualified labels in Kotlin's Lambda functions
Returns and qualified labels in Kotlin's Lambda functions

Time:11-19

I am struggling to understand a concept in kotlin. Looking at this

val lambda = { greeting: String, name: String -> 
    if(greeting.length < 3) return // error: return not allowed here
    
    println("$greeting $name")
}

This would result in an error. Rewriting the lambda expression to this

val lambda = greet@ { greeting: String, name: String -> 
    if(greeting.length < 3) return@greet
    
    println("$greeting $name")
}

It works. And it works because "... return from our lambda to the outer, calling function..."

What I am struggling to understand is, what the outer calling function is. There is no other function, calling lambda. Whats going on under the hood here?

CodePudding user response:

You're right that there is no other function calling lambda right now. What it means is that, when you do decide to call lambda, it will return to the function where you are doing that.

For example, if you have:

fun someFunction() {
    lambda()
    // some other code...
}

Then that return@greet will return to someFunction. someFunction is the "outer, calling function".

Just saying that might not be very meaningful, until you compare this to return without a label. Let's make up a situation where return and return@label are both allowed:

fun main() {
    aMoreMeaningfulExample foo@{
        if (it == 3) return@foo
        println(it)
    }
}

inline fun aMoreMeaningfulExample(lambda: (Int) -> Unit) {
    for (x in 1..5) {
        lambda(x)
    }
    println("Done!")
}

Here, return@foo returns to the "outer, calling function" of the lambda, which is aMoreMeaningfulExample. This means that println(it) will be skipped when it is 3. After returning to aMoreMeaningfulExample, the for loop there will still continue as normal, so you will see the rest of the numbers, and "Done!" being printed.

On the other hand, if you used return, it would return to whatever called main, in other words, terminating the program. You will only see "1" and "2" being printed.

  • Related