0
0
Kotlinprogramming~20 mins

Accessing elements safely in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Safe Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
Anull
Bnone
CIndexOutOfBoundsException
Dbanana
Attempts:
2 left
💡 Hint
Remember that getOrNull returns null if index is out of range, and Elvis operator ?: provides a default.
Predict Output
intermediate
2: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)
A-1
Bnull
C2
DKeyNotFoundException
Attempts:
2 left
💡 Hint
Accessing a missing key in a map returns null, so the Elvis operator provides the default.
🔧 Debug
advanced
2: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)
AThe !! operator forces a non-null assertion and throws NullPointerException if null
BThe variable text is not initialized
CThe safe call operator ?. is missing, so length is accessed directly
DThe println function cannot print null values
Attempts:
2 left
💡 Hint
The !! operator is a way to say 'I am sure this is not null'.
Predict Output
advanced
2: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)
AName cannot be null
B0
C6
Dnull
Attempts:
2 left
💡 Hint
let runs the block only if the value is not null.
Predict Output
expert
2: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)
A0
B-1
CNullPointerException
Dnull
Attempts:
2 left
💡 Hint
Each safe call returns null if the previous value is null, so the Elvis operator provides the default.