Variables & Constants

Variables & Constants

Variables / let-bindings

Aiken has let-bindings for declaring variables. A value can be given a name using the keyword let. Names can be reused by later let-bindings.

Values assigned to let-bindings are immutable, however new bindings can shadow previous bindings.

let x = 1
let y = x
let x = 2
 
y + x == 3

Module constants

Let-bindings aren't allowed in a top-level Aiken module. Yet, Aiken provides module constants as a way to use certain fixed values in multiple places of a Aiken project.

const start_year = 2101
const end_year = 2111

Like all values in Aiken, module constants are immutable. They cannot be used as global mutable state. When a constant is referenced, its value is inlined by the compiler so they can be used in any place where you'd have written a literal to begin with (e.g. when-expression, if/else-expression ...). We'll see some example of that when dealing with control flows.

Constants are quite powerful in Aiken. They can hold (almost) any Aiken expression and are fully evaluated at compile-time. Said differently, you can write something like:

const summer = "Summer"
const autumn = "Autumn"
const winter = "Winter"
const spring = "Spring"
const seasons = [summer, autumn, winter, spring]

Constants can refer to other identifiers such as functions and other constants with one restriction: constants cannot refer to other constants that are defined after them in the file. As such, there's no recursive or mutually recursive constants.

Type annotations

Variables and constants can be given type annotations. These annotations serve as documentation or can be used to provide a more specific type than the compiler would otherwise infer.

const name: ByteArray = "Aiken"
const size: Int = 100
 
let result: Bool = 14 > 42

Documentation

You may add user facing documentation to any constant definition with a documentation comment starting with ///. Markdown is supported and this text will be included with the module's entry in generated HTML documentation.

/// Timeout, in number of **seconds**.
const timeout: Int = 60

When exported as module documentation, constant definitions are alphabetically sorted (in ascending order).