Skip to content

Instantly share code, notes, and snippets.

@abreslav
Created October 10, 2013 11:24
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 abreslav/6916859 to your computer and use it in GitHub Desktop.
Save abreslav/6916859 to your computer and use it in GitHub Desktop.
Non-local returns in Kotlin
// Sometimes you are inside a lambda and want to return a value from some surrounding function (or surrounding lambda)
fun foo(): Any? {
return withNLR(default = 25) {
listOf(1, 2, 3).forEach {
if (it > 2) doReturn(it)
}
}
}
// Here's the implementation of withNLR():
private class NonLocalReturnException(val r: Any?): RuntimeException()
public class NonLocalReturnAvailable<R> {
public fun doReturn(r: R): Nothing = throw NonLocalReturnException(r)
}
public fun withNLR<R>(default: R, body: NonLocalReturnAvailable<R>.() -> Unit): R {
try {
NonLocalReturnAvailable<R>().body()
return default
}
catch (e: NonLocalReturnException) {
[suppress("UNCHECKED_CAST")]
return e.r as R
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment