Predict the output
What does this print?
fun main() = runBlocking {
val ctx = Dispatchers.Default + CoroutineName("first") + CoroutineName("second")
launch(ctx) {
println(coroutineContext[CoroutineName]?.name)
}.join()
}Hint 1 of 2
How many CoroutineName elements can a context hold?
Hint 2 of 2
Which side wins in a + b?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A second
Correct. Context elements are keyed; the right-hand CoroutineName replaces the left one.
Why not the others?
- B first. The left element is replaced by the later one with the same key.
- C first second. A context holds at most one element per key.
- D null. launch keeps the name from the context you passed in.