Skip to content
Kavachकवच

Signatures

● Beginner4 minBefore this: FunctionsSpec 3.5

A function's first lines say what it takes, gives, may fail with, may touch, and promises.

type Account {
    owner: String
    balance: Decimal
}

fn withdraw(account: Account, amount: Decimal) -> Account
    require amount > 0
    require amount <= account.balance
    ensure result.balance == account.balance - amount
{
    account with { balance: account.balance - amount }
}

fn main() {
    const before = Account(owner: "Asha", balance: 500)
    const after = withdraw(before, 120)
    print(after.balance)
}

The program ran and printed:

kavach run signature.kav

380
signature.kav: Kavach code, then what running it prints

Between the result type and the body, a function can state more, always in this order: the errors it can give (!), the capabilities it uses (uses), what callers must ensure (require), what it promises (ensure), and examples (example). Each has its own part of the course.

Reading only the signature tells a reviewer what a function does, without reading its body. That matters when someone else, or an AI, wrote the body.