Kotlin Academy · Lesson

Safe Call ?. and Elvis ?: in Real Code

Chain safe calls and provide fallback values using the Elvis operator.

Lesson 2 of 413 steps

Safe Call ?. and Elvis ?: in Real Code is a free Kotlin Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

Two Operators, Big Impact

The safe call ?. calls a member only if the receiver is non-null. The Elvis operator ?: provides a fallback when the left side is null.

Safe Call Basics

x?.member evaluates to null if x is null; otherwise it accesses member normally.

fun main() {
    val name: String? = "Kotlin"
    val len: Int? = name?.length
    println(len) // 6
    val nope: String? = null
    println(nope?.length) // null
}

Elvis Operator Basics

x ?: default returns x if non-null, otherwise the default on the right.

fun main() {
    val name: String? = null
    val display = name ?: "Anonymous"
    println(display) // Anonymous
}

Combining Safe Call and Elvis

Common idiom: obj?.member ?: default — read or fall back.

fun main() {
    val name: String? = null
    val length = name?.length ?: 0
    println("length = $length") // 0
}

Chaining Safe Calls

Chain ?. through multiple levels — the whole expression short-circuits to null if any link is null.

class Address(val city: String?)
class User(val address: Address?)
fun main() {
    val u: User? = User(Address(null))
    val city = u?.address?.city ?: "Unknown"
    println(city) // Unknown
}

Elvis Throwing on the Right

The right side of Elvis can be any expression, including throw — useful for required-value checks.

fun loadConfig(path: String?): String {
    val p = path ?: throw IllegalArgumentException("path required")
    return "loaded $p"
}
fun main() {
    println(loadConfig("/etc/app"))
    // loadConfig(null) // throws
}

Safe Call with Methods

Safe calls work on any method, not just property access.

fun main() {
    val raw: String? = "  hello  "
    val cleaned = raw?.trim()?.uppercase() ?: ""
    println(cleaned) // HELLO
}

Safe Call in Conditions

You can use safe calls inside conditions. Combine with Elvis for default booleans.

fun main() {
    val name: String? = "Alice"
    if (name?.startsWith("A") == true) {
        println("Starts with A")
    }
}

Elvis with return

Use Elvis with return for guard clauses: bail out early if a required value is null.

fun process(input: String?) {
    val safe = input ?: return
    println("processing $safe")
}
fun main() {
    process("abc")
    process(null) // returns silently
}

Elvis with continue/break

Inside loops, Elvis can short-circuit to continue or break for terse null handling.

fun main() {
    val items: List<String?> = listOf("a", null, "b", null, "c")
    for (item in items) {
        val v = item ?: continue
        print("$v ")
    }
    println() // a b c
}

Practical: Configuration Lookup

Safe call + Elvis combine for a one-liner that reads optional config with a default.

class Config(val timeoutMs: Int?, val host: String?)
fun main() {
    val cfg: Config? = Config(null, "prod.example.com")
    val timeout = cfg?.timeoutMs ?: 5000
    val host = cfg?.host ?: "localhost"
    println("$host @ $timeout ms")
}

Quick Check

What does user?.email ?: "unknown" evaluate to when user is null?

Recap

Combine safe call (?.) and Elvis (?:) for concise null-safe code. Use Elvis with throw or return for guard clauses that bail out early on missing data.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Safe Call ?. and Elvis ?: in Real Code” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “Safe Call ?. and Elvis ?: in Real Code”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “Safe Call ?. and Elvis ?: in Real Code”?

Chain safe calls and provide fallback values using the Elvis operator. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Safe Call ?. and Elvis ?: in Real Code” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Nullable Types and the ? Modifier
  2. Safe Call ?. and Elvis ?: in Real Code
  3. let, also, and run with Nullable Receivers
  4. !! Operator: When and Why to Avoid It
← Back to Kotlin Academy