Challenge - 5 Problems
Kotlin Null Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code with null safety?
Consider the following Kotlin code snippet. What will it print when run?
Kotlin
fun main() { val name: String? = null println(name?.length ?: "No name") }
Attempts:
2 left
💡 Hint
Look at the safe call operator and the Elvis operator usage.
✗ Incorrect
The variable 'name' is nullable (String?). The safe call operator '?.' checks if 'name' is null before accessing 'length'. Since 'name' is null, the Elvis operator '?:' returns "No name" instead of throwing an error.
🧠 Conceptual
intermediate2:00remaining
Why does Kotlin distinguish between nullable and non-nullable types?
Why is it important that Kotlin has separate types for nullable and non-nullable variables?
Attempts:
2 left
💡 Hint
Think about common errors in other languages caused by null values.
✗ Incorrect
Kotlin's type system forces developers to explicitly handle nullable types, which helps avoid null pointer exceptions that are common in many other languages.
🔧 Debug
advanced2:00remaining
What error does this Kotlin code produce?
Examine the code below. What error will the Kotlin compiler report?
Kotlin
fun main() { val text: String = null println(text.length) }
Attempts:
2 left
💡 Hint
Look at the variable declaration and its assigned value.
✗ Incorrect
The variable 'text' is declared as a non-nullable String but assigned null, which is not allowed. The compiler reports a type mismatch error.
📝 Syntax
advanced2:00remaining
Which Kotlin code snippet correctly uses the safe call operator?
Select the code snippet that safely accesses the length of a nullable String variable 'input'.
Attempts:
2 left
💡 Hint
Safe call operator is used with '?.' syntax.
✗ Incorrect
Option A uses the safe call operator '?.' which safely accesses 'length' only if 'input' is not null, otherwise returns null.
🚀 Application
expert3:00remaining
What is the output of this Kotlin code demonstrating null safety with let?
Analyze the following Kotlin code and select the output it produces.
Kotlin
fun main() { val name: String? = "Kotlin" name?.let { println("Name length is ${it.length}") } ?: println("Name is null") }
Attempts:
2 left
💡 Hint
The 'let' function runs only if the variable is not null.
✗ Incorrect
Since 'name' is not null, the 'let' block executes and prints the length of the string 'Kotlin' which is 6.