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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay