W3cubDocs

/Kotlin

AbstractCoroutineContextKey

Platform and version requirements: JVM (1.3), JS (1.3), Native (1.3)
@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

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.

Constructors

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)

<init>

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