androidengineers.Book a session

Advanced Language Features

Contracts (opt-in): callsInPlace, returns

article15 minHard

Contracts describe guarantees the implementation must honor

A contract lets a function communicate selected facts to the compiler, such as a non-null relationship after a successful return. Contracts are not runtime validation; an incorrect declaration can make the compiler trust a false statement.

import kotlin.contracts.*

@OptIn(ExperimentalContracts::class)
fun hasText(value: String?): Boolean {
    contract { returns(true) implies (value != null) }
    return value != null && value.isNotBlank()
}

fun length(value: String?): Int = if (hasText(value)) value.length else 0

The body actually enforces the promised non-null condition. callsInPlace describes invocation guarantees for a supplied lambda, such as exactly once, when the implementation genuinely provides them. It must not describe deferred or repeated work as an immediate single invocation.

Contract capabilities and opt-in requirements vary with Kotlin versions; compile against the project's selected compiler and consult its API documentation.

Exercise

Test null, blank, and populated strings. Explain why returning true for null would be a contract bug even if the declaration itself compiled.

Check: prefer built-in checks when they already express the needed guarantee.

Reference: Contracts API

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Contracts (opt-in): callsInPlace, returns | Kotlin Core Programming | Android Engineers