Created
November 20, 2019 09:39
-
-
Save vitusortner/cde7e205ebbe39d79cf6ba7cf0cab035 to your computer and use it in GitHub Desktop.
Kotlin Guard
This file contains hidden or 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 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