`return` 后跟 @ 和对外部块的引用有什么关系?

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

多次出现 return@something,如下所示:

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

这个@withContext是什么意思?如果我尝试像这样向上移动 return,它不会编译:

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

withContext 使用给定的协程上下文调用指定的挂起块,挂起直到完成,然后 returns 结果。

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

这是表示 return 仅来自 wihtContext 块的一种方式。

“@”只是一个简单的标签,它可以是明确的,例如return @yourOwnLabel,或隐含的,例如,return@withContext、return@forEach 等

这里的 Kotlin 文档中有更多信息:https://kotlinlang.org/docs/returns.html#return-to-labels

这是一个带有上面 link 中的显式标签的示例(修改了标签名称以使其更明显):

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