CodeBlanks Logo Icon CodeBlanks

Contracts

Learn compile-time guarantees with Kotlin contracts.

Contracts

Contracts are commitments that tell the compiler which conditions hold after a function is called. They are written with Kotlin's kotlin.contracts API; it is an experimental API.

The most common use is to declare that a value is non-null once the function returns. Example: contract { returns() implies (x != null) }. Then the call site needs no extra !! or if (x != null) block. Contracts only inform the compiler; they emit no runtime code.

returns() implies

A contract block opens with contract { ... }. The most common clause is returns() implies (condition).

Example: contract { returns() implies (x != null) }. This says: when this function returns normally, x is not null. After a requireNonNull(name) call the compiler treats name as String. A wrong contract causes runtime errors, so write them with care.

Practice Write the requireNonNull function

Define requireNonNull(x: String?): String. Inside it, place a contract { returns() implies (x != null) } clause. In main, after calling requireNonNull(name), write println(name.length).

Starter code

Main.kt
import kotlin.contracts.*

fun requireNonNull(x: String?): String {
    // add the contract
    return x!!
}

fun main() {
    val name: String? = "Ayse"
    requireNonNull(name)
    // print the length
}

Sample solution

Main.kt
fun requireNonNull(x: String?): String {
    contract { returns() implies (x != null) }
    return x!!
}
fun main() {
    val name: String? = "Ayse"
    requireNonNull(name)
    println(name.length)
}

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a contract do?

  • Throws an error at runtime
  • Awaits an async call
  • Generates a new class
  • Gives the compiler a behaviour commitment Correct answer

Explanation: A contract informs the compiler; it emits no runtime code.

2 Complete the contract block

Question
fun requireNonNull(x: String?): String {
    ____ { returns() implies (x != null) }
    return x!!
}
Answer
fun requireNonNull(x: String?): String {
    contract { returns() implies (x != null) }
    return x!!
}

Explanation: contract { } starts a contract.

3 Match contract parts

Term Meaning
contract Contract block
returns() Return clause
implies States result
x != null Non-null guarantee

All lessons in Expert