Consider this Kotlin code using async and await to run two tasks concurrently. What will be printed?
import kotlinx.coroutines.* fun main() = runBlocking { val deferred1 = async { delay(100) "Hello" } val deferred2 = async { delay(50) "World" } println(deferred1.await() + " " + deferred2.await()) }
Remember that async starts both tasks immediately, but await waits for the result.
Both tasks start concurrently. deferred1 delays 100ms, deferred2 delays 50ms. However, deferred1.await() is called first, so the program waits for it to finish before calling deferred2.await(). The output is "Hello World".
What will this Kotlin program print?
import kotlinx.coroutines.* fun main() = runBlocking { val deferreds = (1..3).map { n -> async { delay(10L * n) n * n } } val results = deferreds.awaitAll() println(results.sum()) }
Think about the squares of 1, 2, and 3 and their sum.
The tasks compute 1*1=1, 2*2=4, and 3*3=9. Their sum is 1+4+9=14.
Given this Kotlin coroutine snippet, which option will cause a runtime exception when run?
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async { throw IllegalStateException("Error in coroutine") } try { deferred.await() } catch (e: Exception) { println("Caught: ${e.message}") } }
Think about what happens if exceptions inside async are not caught.
Removing the try-catch means the exception thrown inside async is not caught, causing the program to crash with an IllegalStateException.
Choose the best explanation for why async and await are used in Kotlin coroutines.
Think about concurrency and non-blocking waits.
async starts a coroutine that runs concurrently, and await suspends until the result is ready, all without blocking the main thread.
Which Kotlin code snippet correctly fetches two values concurrently using async and await and prints their sum?
Remember that async returns a Deferred, and you must call await() to get the value.
Option A correctly starts two async coroutines and awaits their results before summing. Option A tries to add Deferred objects directly, causing a type error. Option A adds Deferred objects without awaiting, causing a type error. Option A awaits immediately, so the coroutines run sequentially, not concurrently.