Could someone explained what the Key in the Corout...
# coroutines
a
Could someone explained what the Key in the CoroutineContextHandler is used for? I can’t figure it out from the documentation
m
It's mostly an implementation détail to retrieve the CoroutineExceptionHandler in a CoroutineContext. See https://link.medium.com/sJGX3mKwamb for more details
s
See the CoroutineContext as a (typed) map. You can put and get an Element by providing it a Key. Putting another Element with the same key will replace the current Element, if there is one. By convention (not enforced by the language or the compiler), a subtype of an Element should have companion object that is a subtype of Key.
Copy code
class MyElement(...) : Element {
  ...
  fun hello() { ... }
  companion object : Key<MyElement>
}
...
...
coroutineContext[MyElement] = MyElement(...)
...
coroutineContext[MyElement].hello()
                     ^-- key is companion object
a
Thank you, guys