Challenge - 5 Problems
Safe Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of safe access with nullable list?
Consider the following Kotlin code that tries to access an element safely from a nullable list. What will be printed?
Kotlin
val list: List<String>? = listOf("apple", "banana", "cherry") val fruit = list?.getOrNull(1) ?: "none" println(fruit)
Attempts:
2 left
💡 Hint
Remember that getOrNull returns null if index is out of range, and Elvis operator ?: provides a default.
✗ Incorrect
The list is not null and has an element at index 1 which is "banana". So list?.getOrNull(1) returns "banana" and the Elvis operator is not used.
❓ Predict Output
intermediate2:00remaining
What happens when accessing a missing key safely in a map?
Given this Kotlin code, what will be the output?
Kotlin
val map = mapOf("a" to 1, "b" to 2) val value = map["c"] ?: -1 println(value)
Attempts:
2 left
💡 Hint
Accessing a missing key in a map returns null, so the Elvis operator provides the default.
✗ Incorrect
map["c"] returns null because key "c" is missing. The Elvis operator ?: returns -1 instead.
🔧 Debug
advanced2:00remaining
Why does this safe call cause a NullPointerException?
Look at this Kotlin code snippet. It tries to access the length of a nullable string safely but throws an exception. Why?
Kotlin
val text: String? = null val length = text!!.length println(length)
Attempts:
2 left
💡 Hint
The !! operator is a way to say 'I am sure this is not null'.
✗ Incorrect
Using !! on a null value throws NullPointerException immediately. Safe call ?. should be used to avoid this.
❓ Predict Output
advanced2:00remaining
What is the output when chaining safe calls with let?
What will this Kotlin code print?
Kotlin
val name: String? = "Kotlin" val length = name?.let { it.length } ?: 0 println(length)
Attempts:
2 left
💡 Hint
let runs the block only if the value is not null.
✗ Incorrect
name is "Kotlin", so let runs and returns length 6. Elvis operator is not used.
❓ Predict Output
expert2:00remaining
What is the output of nested safe calls with a null intermediate?
Analyze this Kotlin code and determine the output:
Kotlin
data class Person(val pet: Pet?) data class Pet(val name: String?) val person: Person? = Person(null) val petNameLength = person?.pet?.name?.length ?: -1 println(petNameLength)
Attempts:
2 left
💡 Hint
Each safe call returns null if the previous value is null, so the Elvis operator provides the default.
✗ Incorrect
person is not null, but pet is null, so person?.pet?.name?.length returns null. The Elvis operator returns -1.