Consider this Kotlin coroutine code snippet. What will it print?
import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(100L) println("World!") } println("Hello,") }
Remember that launch starts a coroutine that runs concurrently, and delay suspends it without blocking the main thread.
The launch coroutine starts and delays for 100 milliseconds before printing "World!". Meanwhile, the main coroutine prints "Hello," immediately. So the output is "Hello," first, then "World!" on the next line.
Which reason best explains why coroutines are preferred over traditional threads for asynchronous programming in Kotlin?
Think about resource use and how many tasks you can run at once.
Coroutines are lightweight and managed by the Kotlin runtime, so you can run thousands without the heavy memory and context-switching costs of threads. This makes async programming more efficient.
What runtime error will this Kotlin coroutine code produce?
import kotlinx.coroutines.* fun main() = runBlocking { val job = launch { delay(1000L) println("Task finished") } job.cancel() println("Job cancelled") }
Consider what happens when you cancel a coroutine job before it finishes.
Cancelling a coroutine job stops its execution silently. The program prints "Job cancelled" immediately. The delayed print inside the coroutine never happens, but no exception crashes the program.
Which Kotlin code snippet correctly launches a coroutine that waits 500ms and then prints "Done"?
Check the delay parameter type and the print function used.
The delay function requires a Long parameter, so 500L is correct. Using 500 (Int) causes a type error. Also, println prints with a newline, matching the expected output. Thread.sleep blocks the thread and is not a coroutine suspend function.
Given this Kotlin code, how many coroutines run concurrently?
import kotlinx.coroutines.* fun main() = runBlocking { repeat(3) { launch { delay(100L * it) println("Coroutine $it done") } } }
Think about how launch and repeat work together.
The repeat(3) launches 3 separate coroutines immediately. They run concurrently, each delaying a different amount before printing. So all 3 coroutines run at the same time.