Skip to main content
Kira

Generics

Type parameters are specified in square brackets.

Generic Types

Option[T]           // Option containing type T
Result[T, E]        // Result with success type T and error type E
List[T]             // List of type T
(A, B)              // Tuple of A and B

Built-in Generic Types

These types are automatically available:

type Option[T] =
    | Some(T)
    | None

type Result[T, E] =
    | Ok(T)
    | Err(E)

type List[T] =
    | Cons(T, List[T])
    | Nil

Generic Functions

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
}

Custom Generic Types

You can define your own generic types:

type Pair[A, B] = {
    first: A,
    second: B
}

type Tree[T] =
    | Leaf(T)
    | Branch(Tree[T], Tree[T])