kotlinkotlin-coroutines

What's the deal with `return` followed by @ and reference to outer block?


There are multiple occurrences of return@something, like the following:

    withContext(Dispatchers.IO) {
        doSomething(task)
        return@withContext action(task)
    }

what does this @withContext mean? If I try to move return up, like this, it does not compile:

    return withContext(Dispatchers.IO) {
        doSomething(task)
        action(task)
    }

Solution

  • This is a way to say that the return is just from the withContext block.

    The '@' is simply a label and it can be explicit, e.g. return @yourOwnLabel, or implicit e.g, return@withContext, return@forEach etc.

    There is more info in the Kotlin documentation here: https://kotlinlang.org/docs/returns.html#return-to-labels

    Here is an example with an explicit label from the link above (with the label name modified to make it more obvious):

    fun foo() {
        listOf(1, 2, 3, 4, 5).forEach myLabel@{
            if (it == 3) return@myLabel // local return to the caller of the lambda - the forEach loop
            print(it)
        }
        print(" done with explicit label")
    }