0
0
Kotlinprogramming~10 mins

Async coroutine builder 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 launch a coroutine using the async builder.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred = [1] {
        delay(1000L)
        "Hello"
    }
    println(deferred.await())
}
Drag options to blanks, or click blank then click option'
Aasync
Blaunch
Crun
DwithContext
Attempts:
3 left
💡 Hint
Common Mistakes
Using launch instead of async, which returns Job and not Deferred.
Using run which is not a coroutine builder.
Using withContext which is for context switching, not launching async coroutines.
2fill in blank
medium

Complete the code to start an async coroutine in the IO dispatcher.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred = async([1]) {
        delay(500L)
        42
    }
    println(deferred.await())
}
Drag options to blanks, or click blank then click option'
ADispatchers.Main
BDispatchers.IO
CDispatchers.Default
DDispatchers.Unconfined
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main which is for UI thread.
Using Dispatchers.Default which is for CPU-intensive tasks.
Using Dispatchers.Unconfined which is not recommended for IO.
3fill in blank
hard

Fix the error in the async coroutine builder usage.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred = async {
        delay(1000L)
        [1]
    }
    println(deferred.await())
}
Drag options to blanks, or click blank then click option'
Aprintln("Done")
Breturn "Done"
Cdelay(500L)
D"Done"
Attempts:
3 left
💡 Hint
Common Mistakes
Using return inside lambda causes syntax error.
Using println returns Unit, not the desired result.
Calling delay again does not return the result.
4fill in blank
hard

Fill both blanks to create a map of word lengths for words longer than 3 characters.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val lengths = words.associateWith { word -> word.[1] }
    .filter { (word, length) -> length [2] 3 }
Drag options to blanks, or click blank then click option'
Alength
Bcount
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using count instead of length property.
Using less than instead of greater than in filter.
Filtering on word instead of length.
5fill in blank
hard

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

Kotlin
val words = listOf("pear", "plum", "banana", "kiwi")
val result = words.associate { [1] to [2] }
    .filter { (_, length) -> length [3] 4 }
Drag options to blanks, or click blank then click option'
Aword.uppercase()
Bword.length
C>
Dword.lowercase()
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase instead of uppercase.
Using word instead of word.length for value.
Using less than instead of greater than in filter.