Molten

Generics

Functions, structs, classes and interfaces can take type parameters, written as in TypeScript. Generics are monomorphized like C++ templates: each set of type arguments gets its own C code, so they cost nothing at runtime.

interface Named {
    name(): string;
}

class Tool implements Named {
    name(): string { return "wrench"; }
}

struct Pair<T> {
    a: T;
    b: T;
    first(): T { return this.a; }
}

function identity<T>(x: T): T { return x; }

function firstOf<T>(items: Slice<T>): T | null {
    for (const item of items) return item;
    return null;
}

function label<T extends Named>(item: T): string { return `[${item.name()}]`; }

export function main(): void {
    const p = Pair(1, 2);                 // T inferred as int
    const q = Pair<string>("x", "y");     // or given explicitly
    const items = new Array<int>();
    items.push(3, 4);
    print(identity(p.first()), q.first(), firstOf(items.slice()) ?? 0, label(new Tool()));
}
1 x 3 [wrench]

Rules

  • Type arguments are inferred from the call's arguments when possible; when they can't be, write them: identity<string>(...).
  • A type parameter without a constraint only allows assigning, copying and passing values. Anything else is rejected even if every caller happens to use a type that would work: operator '+' does not accept T and T.
  • T extends SomeInterface allows calling that interface's methods. A type argument that doesn't implement it is an error (int does not satisfy Named).
  • Array<T>, Slice<T>, Map<K, V> and Handle<T> are ordinary generic types.
  • Not available: generic static members, generic methods, generic declared functions, and generic components.
  • Limits: 128 specializations per declaration and 32 levels of nested specialization.

View this page's source on GitHub