Quick Answer

Concise null-coalescing operator ?:

Understanding the Issue

The Elvis operator ?: returns the left expression if it's not null, otherwise the right expression. It's more concise than an if-else null check.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Verbose null check
val len = if (s != null) s.length else 0

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution: Elvis operator
val len = s?.length ?: 0

// Also useful for early returns:
fun process(s: String?) {
    val nonNull = s ?: return
    // nonNull is smart-cast to String
}

Key Takeaways

Use the Elvis operator for concise null handling.