Consider this Kotlin code using async coroutine builder. What will it print?
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async { delay(100) "Hello" } println("Start") println(deferred.await()) println("End") }
Remember that async starts a coroutine immediately and await() waits for its result.
The async block starts immediately but suspends for 100ms. The main coroutine prints "Start" first, then waits for the async result with await(), printing "Hello", and finally prints "End".
What will this Kotlin program print?
import kotlinx.coroutines.* fun main() = runBlocking { val scope = CoroutineScope(Dispatchers.Default) val deferred = scope.async { delay(50) 42 } println("Result: ${deferred.await()}") }
async returns a Deferred that you can await() to get the result.
The async coroutine runs in the Dispatchers.Default scope, delays 50ms, then returns 42. The await() call waits for completion and prints the result.
What will this Kotlin program print?
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async { delay(100) "Done" } println("Before delay") delay(200) println("After delay") }
If you don't call await(), the result is not printed.
The async coroutine runs concurrently but its result is not used. The program prints "Before delay", waits 200ms, then prints "After delay". The "Done" string is never printed.
What will this Kotlin code print?
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async { val inner = async { delay(50) 10 } inner.await() * 2 } println(deferred.await()) }
Inner async returns 10 after delay, outer async multiplies by 2.
The inner async returns 10 after 50ms delay. The outer async awaits inner and multiplies by 2, so the final result is 20.
Choose the statement that best describes the async coroutine builder in Kotlin.
Think about how async returns a Deferred and how await() works.
async immediately starts a coroutine and returns a Deferred object. You must call await() on it to get the result. It does not block the thread and can be cancelled.