0
0
Kotlinprogramming~10 mins

Null safety in collections 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 declare a list that cannot hold null values.

Kotlin
val numbers: List<Int> = listOf(1, 2, 3, [1])
Drag options to blanks, or click blank then click option'
A4
Bnull
C"5"
Dtrue
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to add null to a non-nullable list
Using a string instead of an integer
2fill in blank
medium

Complete the code to declare a list that can hold null values.

Kotlin
val nullableNumbers: List<[1]> = listOf(1, null, 3)
Drag options to blanks, or click blank then click option'
AInt
BAny
CString
DInt?
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-nullable type Int which disallows nulls
Using unrelated types like String
3fill in blank
hard

Fix the error in the code to safely access the first element which might be null.

Kotlin
val first: Int? = nullableNumbers.[1](0)
Drag options to blanks, or click blank then click option'
Aget
BgetOrNull
Cfirst
DelementAt
Attempts:
3 left
💡 Hint
Common Mistakes
Using get which throws an exception if index is invalid
Using first which throws exception if list is empty
4fill in blank
hard

Fill both blanks to create a map that holds nullable values and safely access a value.

Kotlin
val map: Map<String, [1]> = mapOf("a" to 1, "b" to null)
val value: [2]? = map["b"]
Drag options to blanks, or click blank then click option'
AInt?
BInt
Attempts:
3 left
💡 Hint
Common Mistakes
Declaring map values as non-nullable Int when nulls are present
Using wrong types for the value variable
5fill in blank
hard

Fill all three blanks to create a list of nullable strings and filter out nulls safely.

Kotlin
val items: List<[1]> = listOf("apple", null, "banana")
val filtered: List<[2]> = items.filterNotNull()
val firstItem: [3] = filtered[0]
Drag options to blanks, or click blank then click option'
AString?
BString
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-nullable type for the original list
Not filtering nulls before accessing elements