0
0
Kotlinprogramming~20 mins

Elvis operator (?:) for default values in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Elvis Operator 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 the Elvis operator?
Consider the following Kotlin code snippet. What will be printed when it runs?
Kotlin
val name: String? = null
val displayName = name ?: "Guest"
println(displayName)
AGuest
Bnull
Cname
DCompilation error
Attempts:
2 left
💡 Hint
The Elvis operator returns the left value if it is not null; otherwise, it returns the right value.
Predict Output
intermediate
2:00remaining
What does this Kotlin code print with a non-null value and Elvis operator?
Look at this Kotlin code. What will be the output?
Kotlin
val input: String? = "Hello"
val result = input ?: "Default"
println(result)
ADefault
Bnull
CCompilation error
DHello
Attempts:
2 left
💡 Hint
The Elvis operator returns the left value if it is not null.
Predict Output
advanced
2:30remaining
What is the output of this Kotlin code with nested Elvis operators?
Analyze this Kotlin code snippet. What will be printed?
Kotlin
val a: String? = null
val b: String? = null
val c = a ?: b ?: "Fallback"
println(c)
Aa
Bnull
CFallback
DCompilation error
Attempts:
2 left
💡 Hint
Elvis operators can be chained to provide multiple fallback values.
Predict Output
advanced
2:30remaining
What error or output does this Kotlin code produce?
Consider this Kotlin code. What will happen when it runs?
Kotlin
val number: Int? = null
val result = number ?: throw IllegalArgumentException("Number required")
println(result)
APrints null
BThrows IllegalArgumentException with message "Number required"
CPrints 0
DCompilation error
Attempts:
2 left
💡 Hint
The Elvis operator can throw an exception if the left side is null.
🧠 Conceptual
expert
3:00remaining
How many items are in the resulting list after applying this Kotlin code with Elvis operator?
Given this Kotlin code, how many elements does the list 'results' contain after execution?
Kotlin
val inputs: List<String?> = listOf("A", null, "B", null, "C")
val results = inputs.map { it ?: "Unknown" }
A5
B3
C2
D0
Attempts:
2 left
💡 Hint
The map function keeps the list size the same, replacing nulls with "Unknown".