Kotlin Wrap Init and Destroy Code Around Function Reference

April 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 code
dialog.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
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.