@ExperimentalStdlibApi abstract class AbstractCoroutineContextKey<B : Element, E : B> : Key<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
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.
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.
AbstractCoroutineContextKey( baseKey: Key<B>, safeCast: (element: Element) -> E?)
© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-abstract-coroutine-context-key/index.html