Skip to main content
Kira

Functions

In Kira, functions are values. Every function has an explicit type signature.

Function Declaration

fn name(param1: Type1, param2: Type2) -> ReturnType {
    // body
    return result
}

Examples:

fn add(a: i32, b: i32) -> i32 {
    return a + b
}

fn greet(name: string) -> void {
    std.io.println("Hello, " + name + "!")
    return
}

Function Rules

  1. All parameters must have explicit types
  2. Return type must be explicit
  3. Use explicit return statements
// Multi-line function
fn factorial(n: i32) -> i32 {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

Effect Functions

Functions that perform side effects must be marked with effect:

effect fn main() -> void {
    std.io.println("Hello, World!")
}

effect fn read_config() -> Result[Config, string] {
    match std.fs.read_file("config.txt") {
        Ok(content) => { return Ok(parse_config(content)) }
        Err(e) => { return Err(e) }
    }
}

See the Effects System for details.

Generic Functions

Use type parameters in square brackets:

fn identity[T](x: T) -> T {
    return x
}

// Call with explicit type argument
let n: i32 = identity[i32](42)
let s: string = identity[string]("hello")

Multiple type parameters:

fn swap[A, B](pair: (A, B)) -> (B, A) {
    let (a, b): (A, B) = pair
    return (b, a)
}

fn first[A, B](pair: (A, B)) -> A {
    return pair.0
}

Functions as Values

let add: fn(i32, i32) -> i32 = fn(a: i32, b: i32) -> i32 {
    return a + b
}

let result: i32 = add(1, 2)

See Higher-Order Functions for passing and returning functions.