Menu
Coddy logo textTech

Elvis Operator

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 15 of 93.

The safe call operator is great for avoiding crashes, but sometimes you need an actual value instead of null. The Elvis operator ?: lets you provide a default value when an expression is null.

The syntax is simple: place ?: after a nullable expression, followed by the fallback value:

fun main() {
    val name: String? = null
    val displayName = name ?: "Guest"
    println(displayName)  // Prints: Guest
}

If the left side is not null, that value is used. If it's null, the right side becomes the result. This works perfectly with safe calls:

fun main() {
    val text: String? = null
    val length = text?.length ?: 0
    println(length)  // Prints: 0
    
    val greeting: String? = "Hello"
    val greetingLength = greeting?.length ?: 0
    println(greetingLength)  // Prints: 5
}

The operator gets its name because ?: looks like Elvis's hair when viewed sideways. More importantly, it gives you a clean way to convert nullable types into non-nullable values with sensible defaults.

challenge icon

Challenge

Easy

A parcel has an optional tracking label and an optional destination. The starter provides both nullable values. Use ?: to choose "Pending" when the tracking label is missing and "Unassigned" when the destination is missing. Print the chosen label, then the chosen destination, on separate lines.

Try it yourself

fun main() {
    val trackingLabel: String? = null
    val destination: String? = "Harbor"
    // Choose and print the two display values.
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground