DEV Community

Cover image for Accept Suspend and Non-Suspend as Parameter in Kotlin
bright inventions
bright inventions

Posted on • Originally published at brightinventions.pl

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() } 
Enter fullscreen mode Exit fullscreen mode


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() } 
Enter fullscreen mode Exit fullscreen mode


Check out our repo! Hope you enjoyed this Kotlin tip. 🙂


By Łukasz Reszetow, Android Developer @ Bright Inventions

Top comments (0)