The Elvis operator helps you give a default value when something might be missing or null. It keeps your code safe and simple.
Elvis operator (?:) for default values in Kotlin
Introduction
Syntax
Kotlin
val result = value ?: defaultValueThe operator ?: checks if value is null.
If value is not null, it uses value. Otherwise, it uses defaultValue.
Examples
name is null, displayName becomes "Guest".Kotlin
val name: String? = null val displayName = name ?: "Guest"
age is 25 (not null), displayAge is 25.Kotlin
val age: Int? = 25 val displayAge = age ?: 18
safeInput will be "No input provided".Kotlin
val input: String? = readLine() val safeInput = input ?: "No input provided"
Sample Program
This program shows how the Elvis operator gives default values when variables are null.
Kotlin
fun main() { val userName: String? = null val displayName = userName ?: "Anonymous" println("Hello, $displayName!") val userScore: Int? = 42 val finalScore = userScore ?: 0 println("Your score is $finalScore.") }
Important Notes
The Elvis operator is a quick way to avoid writing if-else checks for null.
It only works when the left side can be null.
You can use it with any type, not just strings.
Summary
The Elvis operator ?: provides a default value if something is null.
It helps keep your code clean and safe from null errors.
Use it whenever you want a simple fallback value.
Practice
1. What does the Elvis operator
?: do in Kotlin?easy
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 as a fallback.Final Answer:
Returns the left value if it is not null; otherwise returns the right value -> Option DQuick Check:
Elvis operator = default value if null [OK]
Hint: Elvis operator gives a fallback value if null [OK]
Common Mistakes:
- Thinking it compares two values
- Assuming it throws an error on null
- Confusing it with string conversion
2. Which of the following is the correct syntax to use the Elvis operator in Kotlin?
easy
Solution
Step 1: Recall the correct Elvis operator syntax
The Elvis operator is written as?:without any extra characters or spaces.Step 2: Match the syntax with options
val result = value ?: defaultValue uses?:correctly between the variable and the default value.Final Answer:
val result = value ?: defaultValue -> Option CQuick Check:
Correct Elvis syntax = value ?: defaultValue [OK]
Hint: Elvis operator is ?: exactly, no extra symbols [OK]
Common Mistakes:
- Using single question mark instead of ?:
- Adding extra question marks
- Swapping the order of symbols
3. What will be the output of this Kotlin code?
val name: String? = null val displayName = name ?: "Guest" println(displayName)
medium
Solution
Step 1: Check the value of
The variablenamenameis explicitly set tonull.Step 2: Apply the Elvis operator
Sincenameis null,displayNamegets the default value "Guest".Final Answer:
Guest -> Option BQuick Check:
null ?: "Guest" = "Guest" [OK]
Hint: If left is null, Elvis returns right side [OK]
Common Mistakes:
- Assuming it prints null
- Thinking it prints variable name
- Expecting a compile error
4. Identify the error in this Kotlin code snippet using the Elvis operator:
val input: String? = null val output = input ? "Default"
medium
Solution
Step 1: Examine the operator used
The code uses?instead of the Elvis operator?:.Step 2: Understand correct Elvis operator usage
The Elvis operator must be?:to provide a default value when the left side is null.Final Answer:
Incorrect operator used; should be ?: instead of ? -> Option AQuick Check:
Elvis operator must be ?: not ? [OK]
Hint: Elvis operator always uses ?: not just ? [OK]
Common Mistakes:
- Using single question mark instead of Elvis operator
- Forgetting the default value after ?:
- Assuming nullable variables cause error here
5. Given the following Kotlin code, what will be the value of
finalScore?fun calculateScore(score: Int?): Int {
return score ?: 0
}
val userScore: Int? = 5
val finalScore = calculateScore(userScore ?: 10)hard
Solution
Step 1: Evaluate the expression inside the function call
The argument isuserScore ?: 10. SinceuserScoreis 5 (not null), the expression evaluates to 5.Step 2: Call
The function returns the score if not null, so it returns 5.calculateScorewith 5Final Answer:
5 -> Option AQuick Check:
userScore ?: 10 = 5, function returns 5 [OK]
Hint: Elvis operator picks first non-null value [OK]
Common Mistakes:
- Thinking userScore ?: 10 returns 10
- Confusing function return with argument default
- Assuming null causes error here
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
