DEV Community

Cover image for The Promises Your Compiler Believes: Kotlin Contracts Beyond require and run
Android Expert
Android Expert

Posted on Originally published at Medium

The Promises Your Compiler Believes: Kotlin Contracts Beyond require and run

You have never written contract { }, yet you rely on it every day. This line compiles because of one:

fun render(title: String?) {
    if (title.isNullOrBlank()) return
    binding.title.text = title          // title is String here, not String?
    binding.subtitle.text = title.trim() // no !! anywhere
}
Enter fullscreen mode Exit fullscreen mode

isNullOrBlank() is an ordinary function. Nothing in its signature says "if I return false, the receiver is not null." The compiler knows anyway, because the standard library attached a contract to it. This post covers how contracts work, which ones you already use, how to write your own, and the ways they fail in production when you get them wrong.

1. What a contract actually is

A contract is a small declaration at the top of a function body that tells the compiler something about the function’s behavior that the type system cannot express. The compiler stores it in the Kotlin metadata of the compiled class. At a call site, the data-flow analysis reads it and adds facts to what it already knows.

contract-pipeline

Two properties matter for everything that follows:

  1. Contracts cost nothing at runtime. They are metadata. No bytecode is generated for them.
  2. Contracts are promises, not proofs. The compiler uses them to infer, and mostly does not re-verify the body against them. We will come back to this, because it is where the production incidents live.

There are two families of effects. Returns effects, such as returns() implies (x != null), tell the compiler a fact about the arguments or receiver that holds after the call returns normally, and they produce smart-casts. Call effects, such as callsInPlace(block, EXACTLY_ONCE), tell it how many times and when a lambda runs, and they produce definite-assignment and initialization guarantees.

2. The contracts you already use

stdlib-contracts-map

Returns effects: smart-casts from validation

class CheckoutViewModel(private val payments: PaymentsRepository) : ViewModel() {

    fun onPayClicked(cartId: String?, couponCode: String?) {
        requireNotNull(cartId) { "cartId must be set before paying" }
        // cartId: String from here on

        val coupon = couponCode.takeUnless { it.isNullOrBlank() }
        viewModelScope.launch { payments.pay(cartId, coupon) }
    }
}
Enter fullscreen mode Exit fullscreen mode

requireNotNull declares returns() implies (value != null). Because a normal return is the only way execution reaches the next line, the compiler may treat cartId as non-null afterwards. The same shape powers require(cond), check(cond), and checkNotNull.

isNullOrEmpty and isNullOrBlank use a more careful effect: returns(false) implies (this != null). Only the false result carries information, which is why the smart-cast appears in the else path and after an early return in the true path.

Call effects: val initialized inside a lambda

Without a contract, this would not compile, because the compiler cannot know the lambda runs:

val environmentLabel: String
run {
    environmentLabel = if (BuildConfig.DEBUG) "staging" else "production"
}
println(environmentLabel) // definitely assigned
Enter fullscreen mode Exit fullscreen mode

run, let, apply, also, with, use, synchronized and buildList all declare callsInPlace(block, EXACTLY_ONCE). takeIf and takeUnless make the same promise about their predicate lambda. That promise is what lets a val be assigned inside the lambda, exactly once, and be treated as initialized afterwards.

3. Writing your own

You need two things: the opt-in, and a contract that is the first statement of a block-bodied function. That can be a top-level function or a final member function (see the placement rules in section 4).

Example A: a sealed UI state with a smart-casting predicate

sealed interface UiState<out T> {
    data object Loading : UiState<Nothing>
    data class Content<T>(val data: T) : UiState<T>
    data class Failure(val cause: Throwable) : UiState<Nothing>
}

@OptIn(ExperimentalContracts::class)
fun <T> UiState<T>.hasContent(): Boolean {
    contract { returns(true) implies (this@hasContent is UiState.Content<T>) }
    return this is UiState.Content<T>
}
Enter fullscreen mode Exit fullscreen mode

Call site:

fun bindList(state: UiState<List<Article>>) {
    if (state.hasContent()) {
        adapter.submitList(state.data) // smart-cast to Content<List<Article>>
    }
}
Enter fullscreen mode Exit fullscreen mode

This is useful when the predicate hides a richer check, such as Content that is also non-empty. For a plain type check, a when expression with is is simpler and exhaustive, so reach for a contract only when the name carries domain meaning.

Example B: a tracing wrapper that doesn’t break val initialization

@OptIn(ExperimentalContracts::class)
inline fun <T> traced(section: String, block: () -> T): T {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    Trace.beginSection(section)
    try {
        return block()
    } finally {
        Trace.endSection()
    }
}
Enter fullscreen mode Exit fullscreen mode
val articles: List<Article>
traced("parse-feed") { articles = parser.parse(rawJson) }
adapter.submitList(articles)
Enter fullscreen mode Exit fullscreen mode

Without the contract, every wrapper you write around block() silently loses the ability that run has. Instrumentation helpers (tracing, timing, logging scopes) are the most legitimate use of callsInPlace in app code.

Example C: a guard that returns normally or throws

@OptIn(ExperimentalContracts::class)
fun requireSignedIn(session: Session?) {
    contract { returns() implies (session != null) }
    if (session == null) throw SignedOutException()
}
Enter fullscreen mode Exit fullscreen mode

This gives you a domain-specific requireNotNull whose exception type and message your error handling can recognize.

4. Real-world failure modes

trust-boundary

Failure 1: the contract that drifted away from the code

This is the incident you will actually meet. The function was correct on the day it was written:

@OptIn(ExperimentalContracts::class)
fun Session?.isUsable(): Boolean {
    contract { returns(true) implies (this@isUsable != null) }
    return this != null && expiresAt > clock.now()
}
Enter fullscreen mode Exit fullscreen mode

Months later, someone adds guest browsing:

@OptIn(ExperimentalContracts::class)
fun Session?.isUsable(): Boolean {
    contract { returns(true) implies (this@isUsable != null) }
    return isGuestMode || (this != null && expiresAt > clock.now())   // guests have no session
}
Enter fullscreen mode Exit fullscreen mode

The new body can return true with a null receiver. The contract still says otherwise, so this call site compiles with no warning:

if (session.isUsable()) {
    api.setToken(session.token)   // NullPointerException for guests
}
Enter fullscreen mode Exit fullscreen mode

The compiler believed you. Nothing in the build complains, and the crash only appears on the guest path. Treat an implies clause as part of the function's public API: any edit to the return logic is an edit to the contract.

Failure 2: claiming EXACTLY_ONCE for something that is not

A retry helper runs its block up to three times. Declaring EXACTLY_ONCE is wrong, and the damage is subtle: callers may assign a val inside the lambda and the compiler will accept code that can assign twice at runtime or never at all. The compiler does check some call-count and lambda-leak violations inside the body, which is a useful safety net, but do not rely on it to catch a wishful declaration. Declare the weakest claim that is true: AT_LEAST_ONCE, AT_MOST_ONCE, or no contract.

Failure 3: smart-casts that refuse to appear on mutable state

class SignupForm { var email: String? = null }

fun submit(form: SignupForm) {
    requireNotNull(form.email)
    send(form.email)   // error: smart cast impossible, 'email' is a mutable property
}
Enter fullscreen mode Exit fullscreen mode

The contract is working. The smart-cast is rejected because the compiler cannot prove form.email is unchanged between the two lines: another thread or callback could mutate it. (The compiler's own message says the property "could be mutated concurrently".) Capture the value instead:

val email = requireNotNull(form.email) { "email required" }
send(email)
Enter fullscreen mode Exit fullscreen mode

Teams often “fix” this error with !!, which discards the whole point of the contract. Prefer a local val.

Failure 4: expecting it to work where contracts are not allowed

Contracts are restricted by design, and the restrictions surprise people coming from other languages.

contract-rules

The two that bite most often in Android codebases: contracts are accepted on top-level functions and final member functions, but rejected on interface members and open, abstract or overriding methods, so you cannot attach one to your repository interface or to a method a subclass can override. You also cannot use an expression body (fun f() = ...). Kotlin 2.2.20 added experimental support, behind the -Xallow-contracts-on-more-functions compiler flag, for contracts in property accessors and a few operator functions, but treat those as experimental. If you need the behavior on an interface-typed value, write a top-level extension function.

Failure 5: compiler upgrades and opt-in drift

Because the declaration API is experimental, a Kotlin or K2 compiler upgrade is the moment to re-verify. Smart-cast inference has improved across compiler generations, so behavior that required a workaround before can differ after. If a shared library exposes custom contracts, the safest approach is to pin the Kotlin version used to build it and write the tests below.

5. Testing a promise the compiler won’t check

You need two kinds of tests, and they catch different bugs.

A runtime test of the truth of the implication. For implies, test every input class that the contract mentions:

class SessionContractTest {
    @Test fun `isUsable never returns true for a null session`() {
        listOf(true, false).forEach { guest ->
            val result = withGuestMode(guest) { (null as Session?).isUsable() }
            if (result) fail("contract broken: true returned for null receiver (guest=$guest)")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A compile-time test of the benefit. Keep a small source file in your test set that depends on the smart-cast, with no !!:

fun smartCastStillWorks(session: Session?): String {
    if (session.isUsable()) return session.token
    return ""
}
Enter fullscreen mode Exit fullscreen mode

If someone removes the contract during a refactor, this file stops compiling and the build tells you. It is the cheapest regression test you will write.

6. When to write a contract, and when not to

Write one when:

  • a helper wraps run-style logic and you want callers to keep val initialization (tracing, timing, scoped resources);
  • a validation function is a domain-named alternative to requireNotNull and its exceptions matter;
  • the predicate genuinely lives in one function that many call sites depend on, and the body is simple enough to keep honest.

Avoid one when:

  • a when with is branches gives you exhaustive checking for free;
  • the body is complex, changes often, or has more than one reason to return true;
  • the function is open, overrides something, or lives in a public library you cannot afford to break;
  • you are using it mostly to avoid typing a local val.

Takeaways

  • Contracts are compile-time metadata that teach the compiler facts about your functions. They are why isNullOrEmpty, requireNotNull and run feel native.
  • Returns effects produce smart-casts. Call effects produce definite assignment.
  • The compiler trusts implies claims. A stale contract becomes a null-pointer crash that the build never warned you about.
  • Declare the weakest true claim, keep contracts on simple functions, and guard every one with a runtime test and a compile-time test.

Before your next !! or redundant if, ask whether a five-line contract would let the compiler do the work. Before you write that contract, ask whether you would bet a release on its truth.

🚀 Master Android Architecture: Volume 2, Architecture at Scale

What happens when your app and your team grow? This volume takes NowReading into modularization, Gradle convention plugins, architecture for large teams and legacy migration. It then covers testing strategy, performance and security, and finishes with Kotlin Multiplatform, adaptive layouts, on-device AI and an end-to-end case study. The appendices collect all 26 ADRs, cheat sheets, a pattern comparison and a system design interview guide.

Top comments (0)