0
0
Kotlinprogramming~7 mins

Elvis operator deep usage in Kotlin

Choose your learning style9 modes available
Introduction

The Elvis operator helps you quickly choose a default value when something might be null. It makes your code shorter and easier to read.

When you want to provide a fallback value if a variable is null.
When you want to chain multiple nullable checks in a simple way.
When you want to avoid writing long if-else statements for null checks.
When you want to assign a value that depends on multiple nullable variables.
When you want to return early with a default if a value is missing.
Syntax
Kotlin
val result = value ?: defaultValue

The Elvis operator is written as ?:.

If value is not null, it is used; otherwise, defaultValue is used.

Examples
If name is null, displayName becomes "Guest".
Kotlin
val name: String? = null
val displayName = name ?: "Guest"
If input is null, length is 0; otherwise, it is the length of the string.
Kotlin
val length = input?.length ?: 0
Checks a, then b, then c, and uses "default" if all are null.
Kotlin
val result = a ?: b ?: c ?: "default"
Sample Program

This program shows how to use the Elvis operator in simple cases, chaining multiple nullable variables, and with function calls that might return null.

Kotlin
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")
}
OutputSuccess
Important Notes

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.

Summary

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.