0
0
Kotlinprogramming~5 mins

Elvis operator (?:) for default values in Kotlin

Choose your learning style9 modes available
Introduction

The Elvis operator helps you give a default value when something might be missing or null. It keeps your code safe and simple.

When you want to use a value but it might be null, so you need a backup value.
When reading user input that might be empty or missing.
When working with data from the internet or a database that can be null.
When you want to avoid errors caused by null values in your program.
Syntax
Kotlin
val result = value ?: defaultValue

The operator ?: checks if value is null.

If value is not null, it uses value. Otherwise, it uses defaultValue.

Examples
If name is null, displayName becomes "Guest".
Kotlin
val name: String? = null
val displayName = name ?: "Guest"
Since age is 25 (not null), displayAge is 25.
Kotlin
val age: Int? = 25
val displayAge = age ?: 18
If the user enters nothing (null), 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.")
}
OutputSuccess
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.