The Elvis operator helps you quickly choose a default value when something might be null. It makes your code shorter and easier to read.
Elvis operator deep usage in Kotlin
val result = value ?: defaultValueThe Elvis operator is written as ?:.
If value is not null, it is used; otherwise, defaultValue is used.
name is null, displayName becomes "Guest".val name: String? = null val displayName = name ?: "Guest"
input is null, length is 0; otherwise, it is the length of the string.val length = input?.length ?: 0
a, then b, then c, and uses "default" if all are null.val result = a ?: b ?: c ?: "default"
This program shows how to use the Elvis operator in simple cases, chaining multiple nullable variables, and with function calls that might return null.
fun main() { val userInput: String? = null val defaultInput = "Hello" // Simple Elvis operator val message = userInput ?: defaultInput println("Message: $message") // Chaining Elvis operators val a: String? = null val b: String? = null val c: String? = "Kotlin" val result = a ?: b ?: c ?: "No value" println("Result: $result") // Using Elvis with function calls fun getName(): String? = null val name = getName() ?: "Unknown" println("Name: $name") }
You can chain many Elvis operators to check multiple nullable values in order.
The Elvis operator only works with nullable types and helps avoid explicit null checks.
It is a concise way to provide default values and keep your code clean.
The Elvis operator ?: returns the left value if not null, otherwise the right value.
You can chain Elvis operators to check several nullable values in sequence.
It helps write shorter and clearer code when dealing with nulls.
Practice
What does the Elvis operator ?: do in Kotlin?
Solution
Step 1: Understand the Elvis operator purpose
The Elvis operator?:is used to provide a default value when the left side is null.Step 2: Analyze the behavior
If the left value is not null, it returns that value; otherwise, it returns the right value.Final Answer:
Returns the left value if it is not null; otherwise returns the right value. -> Option BQuick Check:
Elvis operator returns left if not null else right [OK]
- Thinking it compares two values
- Assuming it throws exceptions
- Confusing it with null checks
Which of the following is the correct syntax to use the Elvis operator in Kotlin?
val result = value1 ??: value2
Solution
Step 1: Identify the correct Elvis operator syntax
The Elvis operator in Kotlin is written as?:without spaces.Step 2: Match the syntax with options
val result = value1 ?: value2 uses?:correctly, while others use invalid or incorrect symbols.Final Answer:
val result = value1 ?: value2 -> Option AQuick Check:
Elvis operator syntax is ?: [OK]
- Using single question mark ? instead of ?:
- Using double colon :: by mistake
- Adding extra colons or spaces
What is the output of the following Kotlin code?
val a: String? = null val b: String? = "Hello" val c: String? = null val result = a ?: b ?: c ?: "Default" println(result)
Solution
Step 1: Evaluate the chained Elvis operators
Variableais null, so Elvis operator moves tob.bis "Hello", which is not null.Step 2: Determine the final value
Sincebis not null,resultis assigned "Hello" and the rest is ignored.Final Answer:
Hello -> Option AQuick Check:
Chained Elvis picks first non-null: Hello [OK]
- Assuming it returns null if first is null
- Ignoring chaining and picking last value
- Thinking it causes a compile error
Identify the error in this Kotlin code snippet using the Elvis operator:
val x: String? = null val y: String = x ?: null
Solution
Step 1: Analyze variable types and assignment
Variableyis declared as non-nullableString, butx ?: nullcan be null.Step 2: Understand Kotlin's null safety rules
Assigning null to a non-nullable type causes a compilation error.Final Answer:
Cannot assign null to non-nullable type String -> Option DQuick Check:
Non-nullable cannot hold null [OK]
- Thinking Elvis operator changes nullability
- Assuming nullable can be assigned to non-nullable
- Ignoring Kotlin's strict null safety
Given the following Kotlin code, what will be the output?
fun getName(user: Map): String {
return user["firstName"] ?: user["nickname"] ?: user["lastName"] ?: "Anonymous"
}
val user1 = mapOf("firstName" to null, "nickname" to null, "lastName" to "Smith")
println(getName(user1))Solution
Step 1: Evaluate the map values in order
firstNameandnicknameare null, so Elvis operator moves tolastName, which is "Smith".Step 2: Determine the returned value
SincelastNameis not null, the function returns "Smith".Final Answer:
Smith -> Option CQuick Check:
Elvis chain returns first non-null: Smith [OK]
- Assuming it returns Anonymous despite lastName present
- Confusing null with string "null"
- Thinking map access causes error
Ready to prove it?
Pass the test and this pattern moves unknown
