Kotlin Wrap Init and Destroy Code Around Function Reference

Apr 28, 2019

An example would be I wanted to write a wrapper function to show a busy dialog before code excution, and dismiss the dialog when execution done (to avoid forgetting to dismiss).

Instead of

val dialog = BusyDialog()dialog.show()// excute some codedialog.dismiss()

Code

fun <R> showBusy(dialog: BusyDialog, block: () -> R): R {    val dialog = BusyDialog.show()    return block().apply {       dialog.dismiss()    }}

Usage

showBusy(BusyDialog()) {    // excute some code}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.