0
0
Kotlinprogramming~10 mins

Timeout with withTimeout 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 run a block with a timeout of 1000 milliseconds.

Kotlin
withTimeout([1]) {
    println("Running task")
}
Drag options to blanks, or click blank then click option'
A100
B5000
C1000
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using seconds instead of milliseconds.
Passing zero which means no timeout.
2fill in blank
medium

Complete the code to catch the timeout exception thrown by withTimeout.

Kotlin
try {
    withTimeout(500) {
        Thread.sleep(1000)
    }
} catch ([1]) {
    println("Timeout occurred")
}
Drag options to blanks, or click blank then click option'
ATimeoutCancellationException
BException()
CInterruptedException
DCancellationException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching a generic Exception instead of the specific timeout exception.
Using InterruptedException which is unrelated here.
3fill in blank
hard

Fix the error in the code to properly use withTimeout in a suspend function.

Kotlin
suspend fun runTask() {
    withTimeout([1]) {
        delay(2000)
    }
}
Drag options to blanks, or click blank then click option'
Adelay(1000)
B1000L
C"1000"
D1000
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string instead of an integer.
Passing a Long literal which is allowed but not necessary here.
Passing a function call instead of a number.
4fill in blank
hard

Fill both blanks to create a map of words to their lengths only if length is greater than 3.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val lengths = words.filter { word -> [2] }.associate { word -> word to [1] }
Drag options to blanks, or click blank then click option'
Aword.length
Blen(word)
Cword.length > 3
Dlen(word) > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using Python syntax like len(word).
Using incorrect condition syntax.
5fill in blank
hard

Fill all three blanks to create a map of uppercase words to their lengths only if length is less than 5.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val result = words.filter { word -> [3] }.associate { word -> [1] to [2] }
Drag options to blanks, or click blank then click option'
Aword.uppercase()
Bword.length
Cword.length < 5
Dword.toUpperCase()
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated toUpperCase() instead of uppercase().
Using Python syntax like len(word).
Incorrect condition operator.