Skip to Content
Course content

135: Contracts for Compiler Smart-Casting

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

I was working on a user profile module yesterday and ran into one of those "I know this is true, why doesn't the compiler know this is true" moments. I wanted to pull out the logic for validating if a user's bio is actually usable—meaning it's not null and not just a bunch of whitespace—into its own helper function to keep my main logic clean.

The frustration of the "invisible" null check

I started with something simple. Here is the helper function I wrote and how I tried to use it:

fun isBioUsable(bio: String?): Boolean {
    return bio != null && bio.isNotBlank()
}

fun printBio(userBio: String?) {
    if (isBioUsable(userBio)) {
        // I know for a fact userBio is not null here... right?
        println("User bio length is: ${userBio.length}") 
    }
}

As soon as I typed userBio.length, the IDE screamed at me. "Smart cast to 'String' is impossible, because 'userBio' is a mutable property that could be changed" (or in this case, simply that the compiler doesn't track the result of isBioUsable).

It's annoying. I've explicitly checked for null inside isBioUsable, and that function returned true, so logically, userBio cannot be null inside that if block. But the Kotlin compiler treats functions as black boxes. It sees a function that returns a Boolean, but it has no idea why it returned true or what that implies about the arguments passed into it.

Teaching the compiler a new trick

To fix this, we need to stop treating the function as a black box and instead give the compiler a "contract." This is where kotlin.contracts comes in. I'm going to rewrite the helper to tell the compiler: "If this function returns true, you can bet your life that the argument is not null."

Check out the adjustment here:

import kotlin.contracts.*

fun isBioUsable(bio: String?): Boolean {
    contract {
        returns(true) implies (bio != null)
    }
    return bio != null && bio.isNotBlank()
}

fun printBio(userBio: String?) {
    if (isBioUsable(userBio)) {
        // Now the compiler is happy!
        println("User bio length is: ${userBio.length}") 
    }
}

The contract block is the magic. By adding returns(true) implies (bio != null), I'm explicitly linking the return value of the function to the state of the variable. Now, when the compiler sees if (isBioUsable(userBio)), it doesn't just see a boolean; it sees a guarantee that userBio is now a non-nullable String for the remainder of that scope.

The fine print

Now, before you go adding contracts to every helper function in your project, there are a few things I learned the hard way. First, the contract block must be the very first statement in the function body. If you put a print statement or a variable assignment above it, the compiler will throw a fit.

Second, contracts are currently marked as an experimental feature. Depending on your Kotlin version, you'll likely need to add @OptIn(ExperimentalContracts::class) to your function or your project configuration. It's a bit of a hurdle, but for complex validation logic, it's a lifesaver. It saves you from having to use the non-null assertion operator (!!), which, as you know, is basically a "crash here if I'm wrong" button.

I usually only reach for contracts when I have a validation utility that is used in dozens of places. For a one-off check, a simple if (bio != null) is fine, but once that logic gets reused, contracts keep the call-site clean without sacrificing type safety.




📋 Practical Task

Fixing the Administrative Permission Guard

You are building a permission system for an admin dashboard. You have a helper function called hasAdminPrivileges that checks if a User object is not null and has the "ADMIN" role. However, the compiler is refusing to smart-cast the User object to non-nullable in the main logic, forcing the developer to use !!.

Your Task: Modify the hasAdminPrivileges function to include a contract so that the compiler knows that if the function returns true, the user parameter is definitely not null.

import kotlin.contracts.*

data class User(val name: String, val role: String)

// TODO: Add a contract here to enable smart-casting
fun hasAdminPrivileges(user: User?): Boolean {
    return user != null && user.role == "ADMIN"
}

fun accessSecurePanel(currentUser: User?) {
    if (hasAdminPrivileges(currentUser)) {
        // Currently, this line causes a compilation error:
        // "Smart cast to 'User' is impossible"
        println("Welcome to the secure panel, ${currentUser.name}!")
    } else {
        println("Access Denied.")
    }
}

fun main() {
    val admin = User("Alice", "ADMIN")
    val guest = User("Bob", "GUEST")
    
    accessSecurePanel(admin)
    accessSecurePanel(guest)
    accessSecurePanel(null)
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.