0
0
Kotlinprogramming~10 mins

Why structured concurrency prevents leaks in Kotlin - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to launch a coroutine within a structured scope.

Kotlin
fun main() = runBlocking {
    launch [1] {
        println("Hello from coroutine")
    }
}
Drag options to blanks, or click blank then click option'
A() -> Unit
B{}
C()
D{ }
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of curly braces for the coroutine body.
Trying to pass a function type instead of a lambda block.
2fill in blank
medium

Complete the code to cancel all child coroutines when the parent coroutine is cancelled.

Kotlin
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")
}
Drag options to blanks, or click blank then click option'
Astop
Bterminate
Ccancel
Dend
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop() or terminate() which do not exist.
Not cancelling the job, causing coroutines to leak.
3fill in blank
hard

Fix the error in the code to ensure child coroutines are properly scoped and do not leak.

Kotlin
fun main() {
    val scope = CoroutineScope(Dispatchers.Default)
    scope.launch {
        launch [1] {
            delay(1000)
            println("Child coroutine done")
        }
    }
    Thread.sleep(1500)
}
Drag options to blanks, or click blank then click option'
Ascope
Bthis
CGlobalScope
DrunBlocking
Attempts:
3 left
💡 Hint
Common Mistakes
Using GlobalScope which creates unstructured coroutines that can leak.
Using runBlocking inside launch which is incorrect.
4fill in blank
hard

Fill both blanks to create a structured coroutine scope that automatically cancels child coroutines on failure.

Kotlin
fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught $exception")
    }
    val job = [1](handler) {
        launch {
            throw RuntimeException("Error in child")
        }
    }
    job.[2]()
}
Drag options to blanks, or click blank then click option'
AsupervisorScope
Bcancel
CcoroutineScope
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using supervisorScope which does not cancel siblings on failure.
Using start() which is not a cancellation function.
5fill in blank
hard

Fill all three blanks to create a map of word lengths only for words longer than 3 characters using dictionary comprehension style.

Kotlin
val words = listOf("cat", "house", "dog", "elephant")
val lengths = mapOf([1] to [2] for [3] in words if it.length > 3)
Drag options to blanks, or click blank then click option'
Aword
Bword.length
Dit
Attempts:
3 left
💡 Hint
Common Mistakes
Using it without defining it in the loop.
Mixing up keys and values in the map.