Skip to content

Instantly share code, notes, and snippets.

@renaudcerrato
Last active March 12, 2019 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renaudcerrato/97c781655c95dddb00df243fe39802a7 to your computer and use it in GitHub Desktop.
Save renaudcerrato/97c781655c95dddb00df243fe39802a7 to your computer and use it in GitHub Desktop.
Kotlin Local Returns
// Kotlin's standard library extension
inline fun Array<String>.forEach(action: (String) -> Unit) {
for(str in this) {
action(str)
}
}
val list = listOf("Kotlin", "Java", "Groovy")
// a bare return statement in a lambda called from
// an inline function return from the enclosing function.
fun main() {
list.forEach {
println(it)
if(it == "Kotlin") return // return from main !
}
println("never reached")
}
// because it expands to:
fun main() {
for(str in list) {
println(str)
if(str == "Kotlin") return
}
println("never reached")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment