Challenge - 5 Problems
Null Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing a nullable variable
What is the output of this Kotlin code snippet?
Kotlin
fun main() { val name: String? = null println(name?.length ?: "No length") }
Attempts:
2 left
💡 Hint
Look at the safe call operator and the Elvis operator usage.
✗ Incorrect
The variable name is nullable and set to null. Using name?.length safely returns null instead of throwing an error. The Elvis operator ?: then provides the fallback string "No length".
❓ Predict Output
intermediate2:00remaining
Behavior of non-nullable variable assignment
What happens when you try to assign null to a non-nullable variable in Kotlin?
Kotlin
fun main() { val number: Int = null println(number) }
Attempts:
2 left
💡 Hint
Remember Kotlin's default type nullability.
✗ Incorrect
Kotlin types are non-nullable by default. Assigning null to a non-nullable type causes a compilation error.
🔧 Debug
advanced2:00remaining
Identify the cause of NullPointerException
Why does this Kotlin code throw a NullPointerException at runtime?
Kotlin
fun main() { val text: String? = null val length: Int = text!!.length println(length) }
Attempts:
2 left
💡 Hint
Check the use of the !! operator on a null value.
✗ Incorrect
The !! operator asserts that the value is not null. Since text is actually null, this causes a NullPointerException at runtime.
🧠 Conceptual
advanced2:00remaining
Understanding Kotlin's type system default
Which statement best describes Kotlin's type system regarding nullability?
Attempts:
2 left
💡 Hint
Think about how Kotlin prevents null pointer errors.
✗ Incorrect
Kotlin's type system makes all types non-nullable by default. To allow null values, you must explicitly declare a type as nullable using ?.
❓ Predict Output
expert2:00remaining
Output of complex nullable chaining
What is the output of this Kotlin code?
Kotlin
fun main() { val map: Map<String, String?> = mapOf("key" to null) val length = map["key"]?.length ?: -1 println(length) }
Attempts:
2 left
💡 Hint
Check the safe call and Elvis operator on a nullable map value.
✗ Incorrect
The map contains a key with a null value. The safe call ?.length returns null, so the Elvis operator returns -1.