Home > Back-end >  What's the deal with `return` followed by @ and reference to outer block?
What's the deal with `return` followed by @ and reference to outer block?

Time:03-08

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)
    }

CodePudding user response:

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

The '@' is a 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")
}

CodePudding user response:

withContext calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html

  • Related