0
0
Kotlinprogramming~20 mins

Null safety in collections in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Null Safety Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of safe call with nullable list elements
What is the output of this Kotlin code snippet?
Kotlin
val list: List<String?> = listOf("apple", null, "banana")
val result = list.map { it?.length ?: 0 }
println(result)
A[5, -1, 6]
B[5, null, 6]
C[5, 1, 6]
D[5, 0, 6]
Attempts:
2 left
💡 Hint
Remember the safe call operator ?. returns null if the object is null, and the Elvis operator ?: provides a default value.
Predict Output
intermediate
2:00remaining
Filtering nulls from a list
What will be printed by this Kotlin code?
Kotlin
val items: List<String?> = listOf("cat", null, "dog", null, "bird")
val filtered = items.filterNotNull()
println(filtered)
A[cat, dog, bird]
B[cat, null, dog, null, bird]
C[cat, dog, null, bird]
D[null, null]
Attempts:
2 left
💡 Hint
filterNotNull() removes all null elements from the list.
🔧 Debug
advanced
2:00remaining
Identify the error with nullable map keys
What error does this Kotlin code produce?
Kotlin
val map: Map<String?, Int> = mapOf(null to 1, "two" to 2)
println(map[null])
ACompilation error: Null can not be a key in a Map
BRuntime NullPointerException
CPrints 1
DCompilation error: Map keys must be non-nullable
Attempts:
2 left
💡 Hint
Kotlin allows nullable keys in maps, but accessing them requires care.
Predict Output
advanced
2:00remaining
Result of safe access on nullable list
What is the output of this Kotlin code?
Kotlin
val list: List<String>? = null
val size = list?.size ?: -1
println(size)
AThrows NullPointerException
B-1
Cnull
D0
Attempts:
2 left
💡 Hint
The safe call operator ?. returns null if the object is null, then Elvis operator ?: provides a default.
Predict Output
expert
2:00remaining
Count non-null values in a nullable map
What is the output of this Kotlin code?
Kotlin
val map: Map<String, String?> = mapOf("a" to "apple", "b" to null, "c" to "cat")
val count = map.values.count { it != null }
println(count)
A2
B3
C1
DCompilation error
Attempts:
2 left
💡 Hint
Count how many values in the map are not null.