Challenge - 5 Problems
Elvis Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Elvis operator with nested nullables
What is the output of this Kotlin code snippet?
Kotlin
val a: String? = null val b: String? = "Hello" val c: String? = null val result = a ?: b ?: c ?: "Default" println(result)
Attempts:
2 left
💡 Hint
The Elvis operator returns the first non-null value from left to right.
✗ Incorrect
The expression evaluates from left to right: 'a' is null, so it checks 'b' which is "Hello" (non-null), so it returns "Hello".
❓ Predict Output
intermediate2:00remaining
Elvis operator with function calls
What will be printed by this Kotlin code?
Kotlin
fun getName(): String? = null fun getDefaultName(): String = "Guest" val name = getName() ?: getDefaultName() println(name)
Attempts:
2 left
💡 Hint
Elvis operator calls the right side only if the left side is null.
✗ Incorrect
getName() returns null, so Elvis operator evaluates getDefaultName() which returns "Guest".
❓ Predict Output
advanced2:00remaining
Elvis operator with smart casting and let
What is the output of this Kotlin code?
Kotlin
val input: String? = "Kotlin" val length = input?.let { it.length } ?: -1 println(length)
Attempts:
2 left
💡 Hint
The safe call with let executes only if input is not null.
✗ Incorrect
input is "Kotlin" (not null), so let returns length 6, Elvis operator returns 6.
❓ Predict Output
advanced2:00remaining
Elvis operator with multiple nullable types and side effects
What will be printed by this Kotlin code?
Kotlin
var count = 0 fun getFirst(): String? { count++ return null } fun getSecond(): String? { count++ return "Second" } val result = getFirst() ?: getSecond() ?: "Default" println("$result $count")
Attempts:
2 left
💡 Hint
Elvis operator evaluates left to right and stops at first non-null.
✗ Incorrect
getFirst() returns null and increments count to 1, getSecond() returns "Second" and increments count to 2, so result is "Second" and count is 2.
❓ Predict Output
expert3:00remaining
Complex Elvis operator with nested expressions and nullables
What is the output of this Kotlin code?
Kotlin
data class User(val name: String?, val nickname: String?) fun getUser(): User? = User(null, "Nick") val displayName = getUser()?.name ?: getUser()?.nickname ?: "Unknown" println(displayName)
Attempts:
2 left
💡 Hint
Elvis operator chains check for non-null values from left to right.
✗ Incorrect
getUser() returns User(null, "Nick"). The first call getUser()?.name is null, so Elvis operator checks getUser()?.nickname which is "Nick".