Abstract Coroutine Context Key
Начиная с Kotlin: 1.3
abstract classAbstractCoroutineContextKey<B : CoroutineContext.Element, E : B>(baseKey: CoroutineContext.Key<B>, safeCast: (element: CoroutineContext.Element) -> E?) : CoroutineContext.Key<E>
Устарело
Предупреждение начиная с 2.4
Полиморфные ключи контекста корутин подвержены ошибкам, их трудно правильно реализовать, и они могут побуждать к зависимости от деталей реализации. Предпочтительно получать элемент по его базовому ключу и при необходимости явно приводить его тип либо вводить отдельное свойство-расширение.
Базовый класс для 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
Параметры
экземпляр базового ключа
функция, которая может безопасно привести абстрактный CoroutineContext.Element к конкретному типу E и вернуть элемент, если он является подтипом E, или null в противном случае.
Параметры типа
базовый класс полиморфного элемента
тип элемента, связанный с текущим ключом
Конструкторы
constructor(baseKey: CoroutineContext.Key<B>, safeCast: (element: CoroutineContext.Element) -> E?)
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.coroutines/-abstract-coroutine-context-key/