Challenge - 5 Problems
Elvis Operator 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 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)
Attempts:
2 left
💡 Hint
The Elvis operator returns the left value if it is not null; otherwise, it returns the right value.
✗ Incorrect
Since 'name' is null, the Elvis operator returns the default value "Guest".
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The Elvis operator returns the left value if it is not null.
✗ Incorrect
Since 'input' is "Hello" (not null), the Elvis operator returns "Hello".
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
Elvis operators can be chained to provide multiple fallback values.
✗ Incorrect
Both 'a' and 'b' are null, so the chained Elvis operators return "Fallback".
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
The Elvis operator can throw an exception if the left side is null.
✗ Incorrect
Since 'number' is null, the Elvis operator throws the specified exception.
🧠 Conceptual
expert3: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" }
Attempts:
2 left
💡 Hint
The map function keeps the list size the same, replacing nulls with "Unknown".
✗ Incorrect
The map transforms each element, replacing nulls with "Unknown", but the list size remains 5.