Skip to content

Instantly share code, notes, and snippets.

@ImanX
Last active December 29, 2020 11:11
Show Gist options
  • Save ImanX/1fa85377c5215bacff4003eed8781143 to your computer and use it in GitHub Desktop.
Save ImanX/1fa85377c5215bacff4003eed8781143 to your computer and use it in GitHub Desktop.
Major Extension Function in Kotlin that I use it.
//This generic function mechanism similar to the `guard` statement in Swift but in Kotlin
inline fun <reified T> T?.guard(block: (T?) -> Nothing): T {
return this ?: block(this)
}
//This generic function mechanism simillar to the `apply` difference is that returning Unit.
@OptIn(ExperimentalContracts::class)
inline fun <reified T> T.actually(block: T.() -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
//This generic function mechanism simillar to the `let` difference is that returning Unit.
@OptIn(ExperimentalContracts::class)
inline fun <reified T> T.absolutely(block: (T) -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment