Complete the code to launch a coroutine within a structured scope.
fun main() = runBlocking {
launch [1] {
println("Hello from coroutine")
}
}The launch function expects a lambda block enclosed in curly braces { } to define the coroutine body.
Complete the code to cancel all child coroutines when the parent coroutine is cancelled.
fun main() = runBlocking {
val job = launch {
launch {
repeat(1000) { i ->
println("Coroutine $i is working")
delay(500)
}
}
}
delay(1300)
job.[1]()
println("Main coroutine ends")
}stop() or terminate() which do not exist.The cancel() function cancels the job and all its child coroutines, preventing leaks.
Fix the error in the code to ensure child coroutines are properly scoped and do not leak.
fun main() {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
launch [1] {
delay(1000)
println("Child coroutine done")
}
}
Thread.sleep(1500)
}GlobalScope which creates unstructured coroutines that can leak.runBlocking inside launch which is incorrect.Using scope as the coroutine context for the child ensures it is properly structured and will be cancelled with the parent.
Fill both blanks to create a structured coroutine scope that automatically cancels child coroutines on failure.
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
val job = [1](handler) {
launch {
throw RuntimeException("Error in child")
}
}
job.[2]()
}supervisorScope which does not cancel siblings on failure.start() which is not a cancellation function.coroutineScope creates a structured scope that waits for all children and cancels on failure. Calling cancel() cancels the job properly.
Fill all three blanks to create a map of word lengths only for words longer than 3 characters using dictionary comprehension style.
val words = listOf("cat", "house", "dog", "elephant") val lengths = mapOf([1] to [2] for [3] in words if it.length > 3)
it without defining it in the loop.We use word as the key, word.length as the value, and iterate over word in words. The condition filters words longer than 3 characters.