Challenge - 5 Problems
Null Safety Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember the safe call operator ?. returns null if the object is null, and the Elvis operator ?: provides a default value.
✗ Incorrect
The list contains nullable strings. For each element, we get its length if not null; otherwise, 0. So null becomes 0.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
filterNotNull() removes all null elements from the list.
✗ Incorrect
filterNotNull() returns a list with only non-null elements, so all nulls are removed.
🔧 Debug
advanced2: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])
Attempts:
2 left
💡 Hint
Kotlin allows nullable keys in maps, but accessing them requires care.
✗ Incorrect
Kotlin permits null keys in maps. The code prints the value for the null key, which is 1.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
The safe call operator ?. returns null if the object is null, then Elvis operator ?: provides a default.
✗ Incorrect
list is null, so list?.size is null, and ?: returns -1 as default.
❓ Predict Output
expert2: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)
Attempts:
2 left
💡 Hint
Count how many values in the map are not null.
✗ Incorrect
Only "apple" and "cat" are non-null values, so count is 2.