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

1 1 2 1 1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay