0
0
KotlinConceptIntermediate · 3 min read

What is Contract in Kotlin: Explanation and Example

In Kotlin, a contract is a way to describe the behavior of a function to the compiler, helping it understand conditions like when a function returns or how it affects variable states. Contracts improve code analysis and enable smarter optimizations and checks during compilation.
⚙️

How It Works

Think of a contract in Kotlin like a promise a function makes about what it does. For example, it can promise that if it returns normally, a certain condition is true or that it calls a lambda exactly once. This helps the Kotlin compiler understand your code better, similar to how a friend understands your plans when you clearly explain them.

By declaring these contracts, the compiler can make smarter decisions, like knowing when a variable is definitely initialized or when a certain block of code will run. This reduces errors and makes your code safer without extra checks at runtime.

💻

Example

This example shows a function with a contract that tells the compiler the lambda passed to it is called exactly once. This helps Kotlin understand variable initialization inside the lambda.

kotlin
import kotlin.contracts.*

fun runOnce(block: () -> Unit) {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
}

fun main() {
    var x: Int
    runOnce {
        x = 10
    }
    println(x) // Compiler knows x is initialized here
}
Output
10
🎯

When to Use

Use contracts when you want to give the Kotlin compiler extra information about how your functions behave, especially for functions that affect control flow or variable initialization. This is common in utility functions like custom assertions, resource management, or inline functions that take lambdas.

For example, if you write a function that checks a condition and throws an exception if false, a contract can tell the compiler that after this function returns, the condition is true. This helps avoid redundant null checks or warnings.

Key Points

  • Contracts describe function behavior to the compiler.
  • They improve code safety and analysis without runtime cost.
  • Commonly used with inline functions and lambdas.
  • Help the compiler understand variable initialization and control flow.

Key Takeaways

Kotlin contracts let you tell the compiler about function behavior for better code analysis.
They help the compiler understand when variables are initialized or how lambdas are called.
Use contracts in inline functions to improve safety and reduce unnecessary checks.
Contracts do not affect runtime performance but improve compile-time checks.