Skip to content

Instantly share code, notes, and snippets.

@reitzig
Last active November 6, 2018 15:14
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 reitzig/9925fa463eb1e80aecaebfabf1045231 to your computer and use it in GitHub Desktop.
Save reitzig/9925fa463eb1e80aecaebfabf1045231 to your computer and use it in GitHub Desktop.
Implements a guard function for Kotlin that acts similar to the Swift keyword
import java.lang.RuntimeException
inline fun guard(predicate: Boolean, orElse: () -> Nothing) {
contract {
returns() implies predicate
callsInPlace(orElse, InvocationKind.AT_MOST_ONCE) // probably redundant
}
if (!predicate) {
orElse()
}
}
fun foo(a: Int?) {
guard(a != null) {
return@foo // Option A
return // Option A'
throw RuntimeException("blerg") // Option B
}
println(a + 1) // smart cast!
}
@reitzig
Copy link
Author

reitzig commented Jul 25, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment