Published on

Kotlin How to Exit A Lambda / Closure Early


Using closures/lambdas in Kotlin is awesome. One thing that stumped me at first when using them was how to break out of the closure early. In non-lambda code you simply return to break out of the method you are in:

fun someMethod(): String {
  // a bunch of processing ...
    return "Done!"
  //other code if !someCondition
  return "Did not finish"

But what if you want to do this from inside a lambda?

It turns out it is quite easy and if you use IntelliJ you can use code assist to help you.

The general form to return from a lambda early is return@lambdaName. For example, say I have the following forEach:

someNumberList.forEach { number ->
   //... some code here
  if(someCondition) {
    // we need to break out here

The above is the equivalent of an empty return type i.e. one that forces a void method to exit.

To return a value simply put the value after the return@lambdaName valueToReturn. This value obviously matches with the return type of the method:

fun myAwesomeMethod(): List<String> {
  return { num ->
      return@map ""
    } else {
      return@map "A number! :: $num}"

For more on this see the official documentation here