0
0
KotlinHow-ToBeginner · 3 min read

How to Use Elvis Operator in Kotlin: Simple Guide

In Kotlin, the elvis operator (?:) is used to provide a default value when an expression is null. It helps avoid null pointer exceptions by returning the left side if not null, or the right side if the left is null.
📐

Syntax

The Elvis operator syntax is expression1 ?: expression2. If expression1 is not null, it returns that value; otherwise, it returns expression2 as a default.

kotlin
val result = value ?: defaultValue
💻

Example

This example shows how to use the Elvis operator to assign a default string when a nullable variable is null.

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

Common Pitfalls

One common mistake is using the Elvis operator without understanding that the right side is evaluated only if the left side is null. Also, avoid using it when you want to throw exceptions on null; instead, use the ?: throw pattern.

kotlin
fun main() {
    val input: String? = null
    // Wrong: This will assign null instead of throwing an error
    val result1 = input ?: null

    // Right: Throw exception if null
    val result2 = input ?: throw IllegalArgumentException("Input cannot be null")
    println(result2)
}
Output
Exception in thread "main" java.lang.IllegalArgumentException: Input cannot be null at main.main(main.kt:7)
📊

Quick Reference

Use the Elvis operator to simplify null checks and provide fallback values in a concise way.

UsageDescription
val x = a ?: bReturns a if not null, else b
val y = a ?: throw Exception()Throws exception if a is null
val z = a ?: defaultValueAssigns default if a is null

Key Takeaways

The Elvis operator ?: returns the left value if not null, otherwise the right value.
Use it to provide default values and avoid null pointer exceptions.
The right side is only evaluated if the left side is null.
For throwing exceptions on null, use ?: throw pattern.
It simplifies code by replacing verbose null checks.