Last active
November 6, 2018 15:14
-
-
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
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
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! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also a discussion on the Kotlin forums.