Complete the code to safely access the first element of the list.
val list = listOf(1, 2, 3) val first = list.[1]
The firstOrNull() function returns the first element or null if the list is empty, preventing errors.
Complete the code to safely access the element at index 2.
val list = listOf("a", "b") val element = list.[1](2)
The elementAtOrNull() function returns the element at the given index or null if the index is out of bounds.
Fix the error in safely accessing the last element of the list.
val list = listOf<Int>()
val last = list.[1]()lastOrNull() safely returns the last element or null if the list is empty, avoiding exceptions.
Fill both blanks to create a map of words to their lengths, but only for words longer than 3 characters.
val words = listOf("cat", "elephant", "dog", "lion") val lengths = words.associateWith { [1] } val filtered = lengths.filter { it.value [2] 3 }
it.length gets the length of each word, and filtering with > 3 keeps only words longer than 3 characters.
Fill all three blanks to create a map of uppercase words to their lengths, filtering only words longer than 4 characters.
val words = listOf("apple", "bat", "carrot", "dog") val result = words.associate { word -> [1] to [2] } val filtered = result.filter { it.value [3] 4 }
toUpperCase() instead of uppercase().word.uppercase() converts words to uppercase, word.length gets their length, and filtering with > 4 keeps words longer than 4 characters.