Applying a Label

The problem with implicit labels comes when you have nested calls of the same function type (e.g., a forEach() whose lambda expression contains a forEach()).

You can explicitly label a lambda expression if you like, then use return@ with your custom label.

A label is an identifier plus @, preceding the lambda expression itself:

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

  println("Done!")
}

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

So, here, we have labeled the lambda expression toSender@, so we can use return@toSender to return from just the lambda expression.

Note that break and continue also support labels, both implicit and custom ones, to help control where they go to.


Prev Table of Contents Next

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