<init>

Common
JVM
JS
Native
1.0
AbstractCoroutineContextKey(
    baseKey: Key<B>,
    safeCast: (element: Element) -> E?)

Base class for CoroutineContext.Key associated with polymorphic CoroutineContext.Element implementation. Polymorphic element implementation implies delegating its get and minusKey to getPolymorphicElement and minusPolymorphicKey respectively.

Polymorphic elements can be extracted from the coroutine context using both element key and its supertype key. Example of polymorphic elements:

open class BaseElement : CoroutineContext.Element {
    companion object Key : CoroutineContext.Key<BaseElement>
    override val key: CoroutineContext.Key<*> get() = Key
    // It is important to use getPolymorphicKey and minusPolymorphicKey
    override fun <E : CoroutineContext.Element> get(key: CoroutineContext.Key<E>): E? = getPolymorphicElement(key)
    override fun minusKey(key: CoroutineContext.Key<*>): CoroutineContext = minusPolymorphicKey(key)
}

class DerivedElement : BaseElement() {
    companion object Key : AbstractCoroutineContextKey<BaseElement, DerivedElement>(BaseElement, { it as? DerivedElement })
}
// Now it is possible to query both `BaseElement` and `DerivedElement`
someContext[BaseElement] // Returns BaseElement?, non-null both for BaseElement and DerivedElement instances
someContext[DerivedElement] // Returns DerivedElement?, non-null only for DerivedElement instance

Parameters

B - base class of a polymorphic element

baseKey - an instance of base key

E - element type associated with the current key

safeCast - a function that can safely cast abstract CoroutineContext.Element to the concrete E type and return the element if it is a subtype of E or null otherwise.