Returning Just from a Lambda

If you want the second set of results, but you want the simpler syntax of a lambda expression, you can use a labeled return:

fun somethingifier(items: List<String>) {
  items.forEach {
    if (it.length == 3) return@forEach else println(it)
  }

  println("Done!")
}

fun main() {
  somethingifier(listOf("this", "is", "a", "fun", "bit", "of", "Kotlin"))
}

The function that invokes a lambda expression sets an implicit label, of the same name as the function itself. Here, forEach() is invoking the lambda expression, so we have a forEach label that we can use. return@forEach, therefore, returns from just the lambda expression, not from the entire somethingifier() function.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.