Complete the code to start a coroutine that blocks the current thread until it completes.
import kotlinx.coroutines.* fun main() { [1] { println("Hello from coroutine!") } }
launch which is non-blocking and returns immediately.async without awaiting the result.runBlocking starts a coroutine and blocks the current thread until it finishes. This is useful for bridging regular blocking code with coroutines.
Complete the code to delay inside a runBlocking coroutine.
import kotlinx.coroutines.* fun main() = [1] { println("Start") delay(500) println("End") }
launch which does not block the main thread.delay outside a coroutine scope.runBlocking is used here to create a coroutine scope that blocks the main thread, allowing delay to suspend inside it.
Fix the error in the code by choosing the correct coroutine builder to bridge blocking and suspending code.
import kotlinx.coroutines.* fun main() { [1] { val result = async { delay(100) "Done" }.await() println(result) } }
launch which returns immediately and does not block.GlobalScope.launch which is also non-blocking.runBlocking is needed here to block the main thread until the coroutine completes and the result is printed.
Fill both blanks to create a map of word lengths for words longer than 3 characters inside runBlocking.
import kotlinx.coroutines.* fun main() = [1] { val words = listOf("apple", "bat", "carrot", "dog") val lengths = words.filter { word -> word.length > 3 }.associate { word -> word to [2] } println(lengths) }
launch which does not block the main thread.word.uppercase() instead of length.runBlocking creates the coroutine scope that blocks the main thread. The map comprehension uses word.length to get the length of each word.
Fill all three blanks to create a filtered map of uppercase words and their lengths inside runBlocking.
import kotlinx.coroutines.* fun main() = [1] { val words = listOf("apple", "bat", "carrot", "dog") val filtered = words.filter { word -> word.length > 3 }.associate { word -> word.[2]() to word.[3] } println(filtered) }
lowercase instead of uppercase.launch instead of runBlocking.runBlocking blocks the main thread. word.uppercase() converts words to uppercase keys, and length gets their lengths as values.