Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly returning from lambda expression in Kotlin

Using Spark, I end up with a bit of code like this:

post("/auth/login", { req, res ->
    val body = parseBody(req.body())
    val assertion = body["assertion"]
    if (assertion == null) {
        halt(400)
        return null
    }
    // ...snip...lots more code
})

Which works great, except...it doesn't compile -- I get 'return' is not allowed here.

I could put the remainder of the lambda in an else block, but I'd rather not in the interest of minimizing indentation.

So how do I "short circuit" the lambda to return a null?

like image 648
Max Avatar asked Jul 18 '26 10:07

Max


1 Answers

In my understanding, Lambda cant use return, return is for the function by default.

So you need to use a label to tell the return clause where it will return to. I use this:

f@ {
 ...
 return@f null
}
like image 196
user1453345 Avatar answered Jul 21 '26 04:07

user1453345



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!