Skip to Content
Course content

147: Definitely Non-Nullable Types

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this a dozen times in code reviews. A developer is fighting the compiler, tired of wrapping everything in ?.let { ... } or writing if (x != null) blocks for the fifth time in one function. To make the red squiggly lines go away, they use the "double bang" operator: !!.

It feels like a shortcut. You're essentially telling Kotlin, "I know more than you do. I guarantee this value is not null, so just treat it as a non-nullable type and move on." The problem is that the compiler believes you, but the runtime doesn't care about your promises. If you're wrong, your app crashes instantly.

When Assumptions Lead to NullPointerExceptions

Take a look at this snippet. Imagine we're building a simple user session manager. We have a currentUserId that is nullable because the user might not be logged in yet.

class SessionManager {
    var currentUserId: String? = null

    fun logOut() {
        currentUserId = null
    }

    fun fetchUserData() {
        // We're calling this from a screen that requires login,
        // so we "know" the ID must be there.
        val id = currentUserId!! 
        println("Fetching data for user: $id")
    }
}

fun main() {
    val session = SessionManager()
    // Oops, someone called fetchUserData before the login process finished
    // or after logOut() was triggered by a background timeout.
    session.fetchUserData() 
}

If you run this, you'll get a NullPointerException (NPE). The !! operator converted String? into a "definitely non-nullable" String. But since currentUserId was actually null, Kotlin had no choice but to throw an exception. You've essentially reintroduced the exact problem Kotlin was designed to solve.

Handling the "Impossible" Null Safely

The fix isn't just to stop using !!—though that's a good rule of thumb—but to replace the assumption with a strategy. In the case above, the assumption was "this function is only called when logged in." If that assumption is actually a requirement for the function to work, you should make that requirement explicit.

Instead of forcing the type with !!, use a guard clause. This allows you to handle the "impossible" state gracefully rather than letting the app vanish into a crash report.

class SessionManager {
    var currentUserId: String? = null

    fun logOut() {
        currentUserId = null
    }

    fun fetchUserData() {
        // Use a guard clause to exit early if the assumption is wrong
        val id = currentUserId ?: return println("Error: No active session found.")
        
        // Now, 'id' is automatically smart-cast to a non-nullable String
        println("Fetching data for user: $id")
    }
}

By using the Elvis operator ?:, we've handled the null case. If currentUserId is null, the function returns early. If it's not null, id becomes a definitely non-nullable String for the rest of the function. No crashes, no guessing, and the compiler is happy.

I'll be honest: there are very rare cases where !! is acceptable—usually in unit tests where you've manually set up the state and a null value would indicate a fundamental failure of the test setup. But in production code? Treat !! as a code smell. If you feel the urge to use it, ask yourself: "What happens to the user if I'm wrong about this being non-null?"




📋 Practical Task

Fixing the Fragile Payment Processor

You are working on a payment module where the currencyCode is fetched from a remote configuration file. A previous developer used the !! operator, assuming the config file would always be loaded before any payment is processed. However, during slow network starts, the app is crashing.

Your Task: Rewrite the processPayment function to remove the !! operator. Instead, use a guard clause or the Elvis operator to provide a default currency of "USD" if the currencyCode is null, ensuring the function never throws a NullPointerException.

class PaymentProcessor {
    var currencyCode: String? = null // Loaded asynchronously from server

    fun processPayment(amount: Double) {
        // BUG: This line crashes if currencyCode hasn't loaded yet
        val currency = currencyCode!! 
        println("Processing payment of $amount in $currency")
    }
}

fun main() {
    val processor = PaymentProcessor()
    // Simulate calling the method before the config has loaded
    processor.processPayment(99.99)
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.