AbstractCoroutineContextKey
Deprecated
Warning since 2.4
Polymorphic coroutine context keys are error-prone, difficult to implement correctly, and can encourage depending on implementation details. Prefer retrieving the element by its base key and casting it explicitly when needed or introducing a dedicated extension property.
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 instanceSince Kotlin
1.3Parameters
base class of a polymorphic element
an instance of base key
element type associated with the current key
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.