Chaitanya Gupta (@chaitanya_gupta) on X

X (formerly Twitter) ·

2 min read Original article ↗

user avatar

user avatar

user avatar

Now that we are warmed up, let's have some fun 😜 Kotlin supports lambdas, but lambdas are barred from using a normal return! The last expression in a lambda implicitly returns. kotlinlang.org/docs/lambdas.h…

user avatar

A digression: implicitly returning from the last expression in a function body is great, but I don't know why Kotlin doesn't just do this for everything. Its one of those things that, once you get used to (in my case, thanks to Lisp), you wish it were everywhere.

user avatar

Anyways, back to lambdas. If you really want an explicit return inside a lambda, you have to use something known as "return to labels". Essentially you give a label to the lambda and use the "return@label" syntax to return from it. kotlinlang.org/docs/returns.h…

user avatar

There's also something known as an implicit label 🤷

user avatar

Damn. You say, I just want to use a regular return. Why make me jump through so many hoops? And Kotlin would say, just use "anonymous functions" 🔥 You heard that right - lambdas and anonymous functions are different things in Kotlin 🤦

user avatar

user avatar

Is that all? Of course not! Time for... drumroll... inline functions in Kotlin. Pass a lambda to an inline function, and now you can have bare returns inside a lambda 😳 Note that this is a non-local return - it returns from the calling function instead. kotlinlang.org/docs/inline-fu…

user avatar

If you're like me, at this point you would be asking: when does the insanity end? Well, it doesn't. If the lambda is declared "crossinline", you can't use a non-local return inside it 😂

user avatar

Oh, and one more thing! Kotlin has something called "single-expression functions" where the return is implied (like single expression arrow functions in Javascript, but they look so similar to assignments I have to do a double take every time I see them) kotlinlang.org/docs/functions…

user avatar

We're done - this is all I know about returns in Kotlin 😀 Maybe I am getting old, maybe its just my Lisp brain at work. But things like this have made Kotlin very hard for me to grok. The docs at kotlinlang.org are wonderful, but I wish there were less of it.