0
0
Kotlinprogramming~20 mins

Safe call operator (?.) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Safe Call 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 this Kotlin code using safe call operator?
Consider the following Kotlin code snippet. What will it print when run?
Kotlin
data class Person(val name: String?, val age: Int?)

fun main() {
    val person: Person? = Person(null, 25)
    println(person?.name ?: "Unknown")
}
A25
Bnull
CCompilation error
DUnknown
Attempts:
2 left
💡 Hint
The safe call operator returns null if the object is null, and the Elvis operator provides a default value.
Predict Output
intermediate
2:00remaining
What does this Kotlin code print when using safe call operator with a null object?
Analyze the code below and select the output it produces.
Kotlin
fun main() {
    val text: String? = null
    val length = text?.length ?: -1
    println(length)
}
A-1
B0
Cnull
DCompilation error
Attempts:
2 left
💡 Hint
Safe call returns null if the object is null, then Elvis operator provides fallback.
Predict Output
advanced
2:00remaining
What is the output of this Kotlin code with chained safe calls?
Given the following Kotlin code, what will be printed?
Kotlin
class Address(val city: String?)
class User(val address: Address?)

fun main() {
    val user: User? = User(null)
    println(user?.address?.city ?: "No city")
}
ANo city
Bnull
CCompilation error
DThrows NullPointerException
Attempts:
2 left
💡 Hint
Safe calls chain returns null if any part is null, then Elvis operator provides default.
Predict Output
advanced
2:00remaining
What error does this Kotlin code raise when using safe call operator incorrectly?
Examine the code and determine what error it produces when run.
Kotlin
fun main() {
    val list: List<String>? = null
    val first = list?.get(0)!!
    println(first)
}
ACompilation error
BIndexOutOfBoundsException
CKotlinNullPointerException
DNo error, prints null
Attempts:
2 left
💡 Hint
The '!!' operator forces a non-null assertion and throws if the value is null.
🧠 Conceptual
expert
3:00remaining
How many items are in the resulting list after this Kotlin code runs?
Consider this Kotlin code using safe call operator and list filtering. How many items does 'filtered' contain?
Kotlin
fun main() {
    val list: List<String?> = listOf("apple", null, "banana", null, "cherry")
    val filtered = list.map { it?.length ?: 0 }.filter { it > 5 }
    println(filtered.size)
}
A3
B2
C1
D0
Attempts:
2 left
💡 Hint
Check the length of each string, replace null with 0, then count how many are greater than 5.