What is the contract { } block in Kotlin, and why would you add one to a function?
answer
- First statement of the function body
- kotlin.contracts.contract { }
- @OptIn(ExperimentalContracts::class)
- Tells compiler facts it can't infer
- Compiler trusts, doesn't verify
basics
~20 sA contract is a small block at the start of a function that tells the compiler extra facts about how the function behaves, so it can do smarter checks like smart casts after you call your own function.
solid answer
~40 sA contract { } is a declaration block placed as the very first statement of a function body. Inside it you call the contract DSL (from kotlin.contracts) to describe behavioral facts the compiler cannot infer on its own — e.g. 'if this returns true, the argument was non-null' (returns(...) implies(...)) or 'this lambda is invoked exactly once' (callsInPlace). The compiler trusts these facts and uses them at call sites for smart casts and definite-assignment analysis. The feature is experimental, so you must opt in with @OptIn(ExperimentalContracts::class). The compiler does NOT verify the contract is truthful — it is a promise you make, so an incorrect contract causes unsound behavior.
code
kotlin · 8 linesimport kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@OptIn(ExperimentalContracts::class)
fun checkNotNull(value: Any?) {
contract { returns() implies (value != null) }
if (value == null) throw IllegalStateException()
}go deeper
Knows a contract gives the compiler extra facts and enables smart casts after helper calls.
Can write a simple returns() implies contract and explains the opt-in and first-statement rules.
Articulates that contracts are unchecked, erased at runtime, and distinguishes returns vs callsInPlace effects.
Reasons about soundness risk of false contracts and the experimental/stability trade-offs of shipping them in a public API.
## What a contract is A **contract** is metadata you attach to a function telling the Kotlin compiler facts about the function's behavior that it cannot derive by analyzing the body. Normally the compiler only smart-casts or reasons about code it can see inline. When you extract logic into a helper function, that knowledge is lost at the call site. Contracts let you hand that knowledge back to the compiler. You declare a contract by calling the top-level `contract { }` function from the `kotlin.contracts` package as the **first statement** of the function body. ## The two kinds of effects Inside the `contract { }` block you describe **effects**: - **returns / conditional effects** — `returns() implies (x != null)` means: when this function returns normally, the compiler may assume `x != null`. Used to write custom `require`-like or `isNotNull`-like helpers that propagate smart casts. - **callsInPlace effects** — `callsInPlace(block, InvocationKind.EXACTLY_ONCE)` tells the compiler a lambda parameter is invoked in place (and how many times), enabling `val` initialization inside the lambda and definite-assignment analysis. ## Why it matters ```kotlin import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract @OptIn(ExperimentalContracts::class) fun require(condition: Boolean) { contract { returns() implies condition } if (!condition) throw IllegalArgumentException() } fun use(s: String?) { require(s != null) // After the call, the compiler smart-casts s to String: println(s.length) } ``` Without the contract, the compiler would NOT know that surviving `require(s != null)` proves `s` is non-null. ## Key rules - Must be the **first statement** in the function — before any other code. - Requires opt-in: `@OptIn(ExperimentalContracts::class)` (the `contract` function is `@ExperimentalContracts`). - The compiler **does not check** that your function actually honors the contract; it trusts you. A false contract is unsound. - Contracts are erased; they affect compile-time analysis only and have no runtime cost. - Only allowed on top-level / member functions with a body (not on lambdas, not on accessors with limitations).
- Does the compiler verify your function actually obeys the contract?No. Contracts are unchecked promises; the compiler trusts them. A wrong contract produces unsound smart casts and is a real bug.
- Where in the function must the contract { } call appear?As the very first statement, before any other expression or declaration in the body.
Like a signed affidavit you hand the compiler: it takes your sworn statement at face value without checking the evidence.
saying these in an interview costs you the question
- Thinking the compiler validates the contract against the body
- Believing contracts add runtime checks or cost
- Putting contract { } anywhere other than the first statement
- Confusing contracts with runtime assertions like require/check themselves