Spec-Zone.ru › Kotlin 1.6

<init>

kotlin-stdlib / kotlin.coroutines / AbstractCoroutineContextKey / <init>
Требования к платформе и версии: JVM (1.0), JS (1.0), Native (1.0)
AbstractCoroutineContextKey(
    baseKey: Key<B>, 
    safeCast: (element: Element) -> E?)

Базовый класс для CoroutineContext.Key, связанного с полиморфной реализацией CoroutineContext.Element. Реализация полиморфного элемента подразумевает делегирование методов get и minusKey в getPolymorphicElement и minusPolymorphicKey соответственно.

Полиморфные элементы могут быть извлечены из контекста корутины, используя как ключ элемента, так и ключ его супертипа. Пример полиморфных элементов:

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 - базовый класс полиморфного элемента

baseKey - экземпляр базового ключа

E - тип элемента, связанного с текущим ключом

safeCast - функция, которая может безопасно преобразовать абстрактный CoroutineContext.Element в конкретный тип E и вернуть элемент, если он является подтипом E, или null в противном случае.

© 2010–2022 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/-init-.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API