Kotlin as always comes with a smart and simple solution. 😀 Check out this tip!
Instead of creating two analogous functions just to be able to provide both suspend and regular functions as parameters, like so:
fun doSomethingBeforeAndAfter( nonSuspendAction: () -> Unit ) { somethingBeforeAction() nonSuspendAction() somethingAfterAction() } suspend fun doSomethingBeforeAndAfterForSuspendableActions( suspendAction: suspend () -> Unit ) { somethingBeforeAction() suspendAction() somethingAfterAction() }
If you can define your function as ‘inline’, it will also make it accept both suspend and non-suspend functions as parameters:
inline fun doSomethingBeforeAndAfter( action: () -> Unit ) { somethingBeforeAction() action() somethingAfterAction() }
Check out our repo! Hope you enjoyed this Kotlin tip. 🙂
By Łukasz Reszetow, Android Developer @ Bright Inventions
Top comments (0)