Accept Suspend and Non-Suspend as Parameter in Kotlin
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. š
Looking for software development experts?
case studies
Previous