0
0
Kotlinprogramming~10 mins

WithContext for dispatcher switching in Kotlin - Interactive Code Practice

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

Complete the code to switch to the IO dispatcher using withContext.

Kotlin
suspend fun fetchData() {
    withContext([1]) {
        // perform IO operation
    }
}
Drag options to blanks, or click blank then click option'
ADispatchers.Main
BDispatchers.Default
CDispatchers.IO
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main for IO tasks causes blocking on the main thread.
Using Dispatchers.Default is for CPU-intensive tasks, not IO.
2fill in blank
medium

Complete the code to switch to the Default dispatcher inside withContext.

Kotlin
suspend fun calculate() {
    withContext([1]) {
        // CPU-intensive calculation
    }
}
Drag options to blanks, or click blank then click option'
ADispatchers.Main
BDispatchers.Default
CDispatchers.IO
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO for CPU tasks can cause thread starvation.
Using Dispatchers.Main blocks the UI thread.
3fill in blank
hard

Fix the error in the code by choosing the correct dispatcher for UI updates.

Kotlin
suspend fun updateUI() {
    withContext([1]) {
        // update UI elements
    }
}
Drag options to blanks, or click blank then click option'
ADispatchers.Main
BDispatchers.Unconfined
CDispatchers.IO
DDispatchers.Default
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.IO causes UI update crashes.
Using Dispatchers.Default runs UI code off the main thread.
4fill in blank
hard

Fill both blanks to create a map of words to their lengths, filtering words longer than 4 characters.

Kotlin
val words = listOf("apple", "cat", "banana", "dog")
val lengths = words.associateWith { [1] }
    .filter { it.value [2] 4 }
Drag options to blanks, or click blank then click option'
Ait.length
B>
C<
Dit.count()
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > filters shorter words.
Using it.count() is valid but less common than it.length.
5fill in blank
hard

Fill all three blanks to create a map of uppercase words to their lengths, filtering lengths greater than 3.

Kotlin
val words = listOf("one", "two", "three", "four")
val result = words.associateBy([1]) { [2] }
    .filter { it.value [3] 3 }
Drag options to blanks, or click blank then click option'
Ait.uppercase()
Bit.length
C>
Dit.lowercase()
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase keys instead of uppercase.
Filtering with < instead of >.