Q:

'return' is not allowed here: Kotlin Coroutine launch(UI) block

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res!=null){
            fetchCatalog(context!!)
            catalogActivityCatalog?.refresh()
        }
    }
}

Above code is working fine. I want to avoid the nested part in the if by returning (thereby stopping execution) if res == null, like this,
fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null)return                  //this line changed <---A

        fetchCatalog(context!!)              //moved outside if block
        catalogActivityCatalog?.refresh()    //moved outside if block
    }
}

It says 'return' is not allowed here when I use return in the line indicated by <--A
Is there a keyword to exit launch block in here?
What is the alternative that can be used here instead of return?

A:

The destination of the return has to be specified using return@...
fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null)return@launch     //return at launch

        fetchCatalog(context!!)              
        catalogActivityCatalog?.refresh()    
    }
}

A:

You must create a label to which you apply the return statement, like return@label:
fun onYesClicked(view: View) {

    label@launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null) return@label                   //this line changed <---A

        fetchCatalog(context!!)              //moved outside if block
        catalogActivityCatalog?.refresh()    //moved outside if block
    }
}

This is the Kotlin way to return from a lambda.

