Created
October 10, 2013 11:24
-
-
Save abreslav/6916859 to your computer and use it in GitHub Desktop.
Non-local returns in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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