Last active
December 29, 2020 11:11
-
-
Save ImanX/1fa85377c5215bacff4003eed8781143 to your computer and use it in GitHub Desktop.
Major Extension Function in Kotlin that I use it.
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
//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