为什么 kotlin.coroutines.CoroutineContext.Element 继承自 kotlin.coroutines.CoroutineContext

mds*_*ubi 3 kotlin kotlin-coroutines

我们可以CoroutineContext在从构建器函数创建协程时提供一个可选选项launch,如下所示。

launch(Dispatchers.Unconfined) { // not confined -- will work with main thread
    println("Unconfined      : I'm working in thread ${Thread.currentThread().name}")
    delay(500)
    println("Unconfined      : After delay in thread ${Thread.currentThread().name}")
}
Run Code Online (Sandbox Code Playgroud)

其中一个值是Dispatchers.Unconfined. 我以为Dispatchers.Unconfined会继承,CoroutineContext而且确实如此。但以一种非常复杂的方式,我不太清楚。添加了类层次结构的屏幕截图。

在此输入图像描述

它继承自CoroutineContext.Element相反。这是CoroutineContext. 这个嵌套接口继承了外部/父接口,并且所有有用的实现都CoroutineContext实现了这个嵌套接口。

我不确定为什么会使用这种机制,或者在其他地方使用或可以使用这种模式。嵌套接口 AFAIK 唯一用于创建新名称空间的地方,例如Map.Entry. 官方文档也说得很少,

    /**
     * An element of the [CoroutineContext]. An element of the coroutine context is a singleton context by itself.
     */
Run Code Online (Sandbox Code Playgroud)

不太确定是什么An element of the coroutine context is a singleton context by itself.意思。

我知道这是一个好奇的问题。所以不需要及时响应。但任何帮助将不胜感激。

Rom*_*rov 5

协程上下文是一组元素。协程上下文的一个元素本身就是一个单例上下文。这意味着当将其视为集合(作为协程上下文)时,元素代表单个元素集(也称为单例)。