0
0
KotlinConceptBeginner · 3 min read

What is Elvis Operator in Kotlin: Simple Explanation and Example

The 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.

kotlin
fun main() {
    val name: String? = null
    val displayName = name ?: "Guest"
    println("Hello, $displayName!")
}
Output
Hello, Guest!
🎯

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.

Key Takeaways

The Elvis operator ?: provides a simple way to handle null values by supplying a default.
It helps avoid null pointer exceptions and keeps code concise.
Use it whenever you want to ensure a variable has a safe fallback value.
It improves code readability by reducing explicit null checks.