Kotlin Kotlin Coroutines 1 — Questions and Answers
Question 1: What keyword is used to define a suspending function in Kotlin?
- async
- suspend (Correct answer)
- coroutine
- await
Correct answer: suspend
The `suspend` keyword marks a function that can be paused and resumed, making it usable within coroutines.
Question 2: Which coroutine builder launches a new coroutine and returns a Job?
- async
- launch (Correct answer)
- runBlocking
- withContext
Correct answer: launch
`launch` is a coroutine builder that starts a new coroutine and returns a `Job` handle for managing it.
Question 3: What does the `async` coroutine builder return?
- Job
- Deferred (Correct answer)
- CompletableFuture
- Flow
Correct answer: Deferred
`async` launches a coroutine and returns a `Deferred<T>` object, which represents a future result retrievable via `await()`.
Question 4: Which coroutine scope is used to run coroutines that block the current thread?
- GlobalScope
- CoroutineScope
- runBlocking (Correct answer)
- MainScope
Correct answer: runBlocking
`runBlocking` creates a coroutine scope that blocks the current thread until all coroutines inside it complete.
Question 5: What is the purpose of `withContext` in Kotlin coroutines?
- To launch a new coroutine
- To switch the coroutine dispatcher without creating a new coroutine (Correct answer)
- To cancel a coroutine
- To collect a Flow
Correct answer: To switch the coroutine dispatcher without creating a new coroutine
`withContext` suspends the current coroutine and switches to a different dispatcher or context, resuming on the original dispatcher when done.
Question 6: Which dispatcher should be used for CPU-intensive operations in Kotlin coroutines?
- Dispatchers.Main
- Dispatchers.IO
- Dispatchers.Default (Correct answer)
- Dispatchers.Unconfined
Correct answer: Dispatchers.Default
`Dispatchers.Default` is backed by a shared pool of threads optimized for CPU-intensive computations.
What keyword is used to define a suspending function in Kotlin?