Complete the code to launch a coroutine using the async builder.
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = [1] { delay(1000L) "Hello" } println(deferred.await()) }
The async builder starts a coroutine that returns a result as a Deferred object. You can then call await() to get the result.
Complete the code to start an async coroutine in the IO dispatcher.
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async([1]) { delay(500L) 42 } println(deferred.await()) }
Dispatchers.IO is used for IO-bound tasks like file or network operations. It runs coroutines on a shared pool of threads optimized for IO.
Fix the error in the async coroutine builder usage.
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async { delay(1000L) [1] } println(deferred.await()) }
The last expression inside the async block is the result returned as Deferred. Using return is not allowed inside lambda. Just put the value as the last expression.
Fill both blanks to create a map of word lengths for words longer than 3 characters.
val words = listOf("apple", "bat", "carrot", "dog") val lengths = words.associateWith { word -> word.[1] } .filter { (word, length) -> length [2] 3 }
length property gives the length of the string. We filter to keep only words with length greater than 3.
Fill all three blanks to create a map of uppercase words to their lengths, filtering lengths greater than 4.
val words = listOf("pear", "plum", "banana", "kiwi") val result = words.associate { [1] to [2] } .filter { (_, length) -> length [3] 4 }
We map each word to uppercase as key and its length as value, then filter lengths greater than 4.