https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Jeff Lockhart

03/18/2024, 7:00 PM
Is there an API that can accomplish
coroutineContext[CoroutineDispatcher]
without requiring
@OptIn(ExperimentalStdlibApi::class)
? CC: @Blake
s

Sam

03/19/2024, 7:50 AM
Copy code
coroutineContext[ContinuationInterceptor] as? CoroutineDispatcher
gratitude thank you 1
j

Jeff Lockhart

03/19/2024, 4:36 PM
Interesting, so it's only
AbstractCoroutineContextKey
, which
CoroutineDispatcher
implements, that's marked
ExperimentalStdlibApi
. But
CoroutineContext.Key
is not a
ExperimentalStdlibApi
, even though
AbstractCoroutineContextKey
is the base class for
CoroutineContext.Key
. 🤔 What's the difference between these APIs? And why is one experimental, and the other not?
plus1 1
s

Sam

03/19/2024, 4:41 PM
It comes down to the idea of "polymorphic" context elements. The base type for all continuation interceptors, including dispatchers, is
ContinuationInterceptor
, and that's just a regular coroutine context element with a regular key. Nothing experimental or unexpected. A
CoroutineDispatcher
is a subtype of
ContinuationInterceptor
. So when we write
coroutineContext[CoroutineDispatcher]
, we're looking not just for a
ContinuationInterceptor
, but for a specific subtype of interceptor. That means
CoroutineDispatcher.Key
is a special type of key, sort of like a "sub-key" of
ContinuationInterceptor.Key
. I guess the exact specifics of what this means and how it should work are the bit that's experimental.
j

Jeff Lockhart

03/19/2024, 4:57 PM
Thanks, this makes more sense now. I asked about the API being experimental a while back. I'm curious about some of those ways it's "easy to get wrong". To me, it seems less intuitive if you composed a
CoroutineContext
with a
CoroutineDispatcher
, but then can't decompose it using the same type. Rather, you have to identify the supertype that implements
CoroutineContext.Key
directly and cast it, obfuscating the code's intent as well.