What is Elvis Operator in Kotlin: Simple Explanation and Example
Elvis operator in Kotlin is ?:, used to provide a default value when an expression is null. It helps avoid null pointer errors by returning the left value if not null, or the right value otherwise.How It Works
The Elvis operator ?: acts like a safety net for null values. Imagine you ask a friend for their phone number, but if they don’t have one, you want to use your own number instead. The Elvis operator does the same in code: it checks if a value is null, and if it is, it gives you a backup value.
It’s a shortcut for writing an if-else statement that checks for null. Instead of writing multiple lines to check if something is null and then assign a default, you use ?: to do it in one simple expression. This keeps your code clean and easy to read.
Example
This example shows how the Elvis operator returns a default message if the name is null.
fun main() {
val name: String? = null
val displayName = name ?: "Guest"
println("Hello, $displayName!")
}When to Use
Use the Elvis operator when you want to provide a fallback value for nullable variables. It is especially useful when dealing with user input, database results, or any data that might be missing or null.
For example, if you fetch a user’s profile picture URL that might be null, you can use the Elvis operator to show a default image URL instead. This prevents your app from crashing and improves user experience by handling missing data gracefully.
Key Points
- The Elvis operator is
?:and helps handle null values easily. - It returns the left side if not null, otherwise the right side.
- It simplifies code by replacing longer null checks.
- Commonly used to provide default values for nullable variables.