0
0
Kotlinprogramming~10 mins

Accessing elements safely 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 safely access the first element of the list.

Kotlin
val list = listOf(1, 2, 3)
val first = list.[1]
Drag options to blanks, or click blank then click option'
Afirst()
Bget(0)
CfirstOrNull()
DelementAt(0)
Attempts:
3 left
💡 Hint
Common Mistakes
Using get(0) which throws an exception if the list is empty.
Using first() which throws an exception if the list is empty.
2fill in blank
medium

Complete the code to safely access the element at index 2.

Kotlin
val list = listOf("a", "b")
val element = list.[1](2)
Drag options to blanks, or click blank then click option'
AgetOrElse
Bget
CelementAt
DelementAtOrNull
Attempts:
3 left
💡 Hint
Common Mistakes
Using get(2) which throws an exception if index is out of bounds.
Using elementAt(2) which throws an exception if index is invalid.
3fill in blank
hard

Fix the error in safely accessing the last element of the list.

Kotlin
val list = listOf<Int>()
val last = list.[1]()
Drag options to blanks, or click blank then click option'
AlastOrNull
Blast
CgetLast
DelementAt
Attempts:
3 left
💡 Hint
Common Mistakes
Using last() which throws an exception if the list is empty.
Using elementAt() without checking index.
4fill in blank
hard

Fill both blanks to create a map of words to their lengths, but only for words longer than 3 characters.

Kotlin
val words = listOf("cat", "elephant", "dog", "lion")
val lengths = words.associateWith { [1] }
val filtered = lengths.filter { it.value [2] 3 }
Drag options to blanks, or click blank then click option'
Ait.length
B>
C<
Dit.size
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the filter condition.
Using it.size which is not a property of String.
5fill in blank
hard

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

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val result = words.associate { word -> [1] to [2] }
val filtered = result.filter { it.value [3] 4 }
Drag options to blanks, or click blank then click option'
Aword.uppercase()
Bword.length
C>
Dword.toUpperCase()
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated toUpperCase() instead of uppercase().
Using < instead of > in the filter condition.