'When calling CoroutineScope.launch, how is Dispatchers.Default converted to a CoroutineContext?

I'm trying to understand coroutine scopes and have the following code:

launch(Dispatchers.Default) { ... }

The signature for launch is:

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

And the type of Dispatchers.Default is:

public abstract class CoroutineDispatcher :
    AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor

Neither AbstractCoroutineContextElement or ContinuationInterceptor implement CoroutineContext so how is the compiler able to coerce Dispatchers.Default into a CoroutineContext when launch is called?



Solution 1:[1]

Dispatchers.Default is a CoroutineContext.

AbstractCoroutineContextElement implements CoroutineContext.Element which implements CoroutineContext.

Put another way, a CoroutineContext has a set of Elements, and each one is a CoroutineContext in its own right.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 donturner