Complete the code to run a block with a timeout of 1000 milliseconds.
withTimeout([1]) { println("Running task") }
The withTimeout function takes the timeout duration in milliseconds. Here, 1000 means 1 second.
Complete the code to catch the timeout exception thrown by withTimeout.
try { withTimeout(500) { Thread.sleep(1000) } } catch ([1]) { println("Timeout occurred") }
The withTimeout function throws TimeoutCancellationException when the timeout expires.
Fix the error in the code to properly use withTimeout in a suspend function.
suspend fun runTask() {
withTimeout([1]) {
delay(2000)
}
}The timeout duration must be an integer number of milliseconds. Using 1000 is correct. Quotes make it a string which is invalid.
Fill both blanks to create a map of words to their lengths only if length is greater than 3.
val words = listOf("apple", "bat", "carrot", "dog") val lengths = words.filter { word -> [2] }.associate { word -> word to [1] }
In Kotlin, word.length gets the length of the string. The condition word.length > 3 filters words longer than 3 characters.
Fill all three blanks to create a map of uppercase words to their lengths only if length is less than 5.
val words = listOf("apple", "bat", "carrot", "dog") val result = words.filter { word -> [3] }.associate { word -> [1] to [2] }
toUpperCase() instead of uppercase().Use word.uppercase() to convert to uppercase in Kotlin. word.length gets length. The condition word.length < 5 filters words shorter than 5.