Skip to content

Instantly share code, notes, and snippets.

@vitusortner
Created November 20, 2019 09:39
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 vitusortner/cde7e205ebbe39d79cf6ba7cf0cab035 to your computer and use it in GitHub Desktop.
Save vitusortner/cde7e205ebbe39d79cf6ba7cf0cab035 to your computer and use it in GitHub Desktop.
Kotlin Guard
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun guard(predicate: Boolean, block: () -> Nothing) {
contract {
returns() implies predicate
callsInPlace(block, InvocationKind.AT_MOST_ONCE)
}
if (!predicate) block()
}
inline fun <T> guard(receiver: T?, block: () -> Nothing): T {
if (receiver == null) block()
return receiver
}
@ExperimentalContracts
fun main() {
val nullable: String? = null
guard(nullable != null) {
return
}
nullable.length
val foo = guard(nullable) {
return
}
foo.length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment