Functions and Closures

Declaration and calls

Parameters pair names with types; the return type follows a colon. A function without a return type returns Void. Arguments evaluate left to right. A function declaring : Int returns an Int on every path; any other type is an E304 error with expected/got labels.

.rnx
fn add(a: Int, b: Int): Int {
    return a + b;
}

fn greet(name: String) {
    println!("hello,", name);
}

greet("ore");
println!(add(20, 22));

Return type inference applies where the body determines the type; explicit annotations are required on pub signatures and recommended everywhere a mismatch would otherwise surface at a distance.

Default values and named arguments

Trailing parameters declare defaults, filled in when the caller omits them. Any argument may pass by name after the positional ones. A mandatory parameter after a defaulted one is an error, as are unknown or duplicate names. Methods follow the same rules. Defaults compile away: the callee always receives plain positional values.

.rnx
fn configure(host: String, port: Int = 8080, secure: Bool = false): String {
    let sec = "http";
    if (secure) {
        sec = "https";
    }
    return "${sec}://${host}:${port}";
}

println!(configure("api.dev"));
println!(configure("api.dev", secure: true));
println!(configure("api.dev", port: 9000, secure: true));

Generic functions

Type parameters in angle brackets solve from argument types at each call, or pass explicitly. Parameters erase to a shared representation, so one definition serves every type. A parameter that cannot be inferred, or two arguments forcing different types onto one parameter, is a compile error naming the parameter.

.rnx
fn identity<T>(val: T): T {
    return val;
}

println!(identity(42));
println!(identity("hi"));

Lambdas and closures

A lambda is (params) => body, with the single-identifier shorthand x => body. The body is one expression (implicit return) or a block. fn(...) => ... is rejected with E105: fn declares named functions with block bodies only.

.rnx
let factor = 10;
let mult = (x: Int) => x * factor;
assert(mult(5) == 50, "capture");

Closures capture their environment by value and are first-class: they pass as arguments, store in fields, and call anywhere. Captures keep heap values alive for as long as the closure lives, including when the closure is stored in a field, an array, or another closure. Parameter annotations may be omitted when the call site determines the shape: map/filter infer the element type from the receiver, and plain functions infer from fn-typed parameters.

.rnx
fn apply(x: Int, f: fn(Int): Int): Int {
    return f(x);
}

let nums = [1, 2, 3];
assert(nums.map((n) => n * 2)[2] == 6, "inferred map");
assert(apply(5, (n) => n * 2) == 10, "inferred HOF");

A generic function can take a fn-typed parameter and call it with the type parameter. The closure keeps its concrete signature at the call site, and its scalar result is boxed when the erased callee returns it as Any:

.rnx
fn twice<T>(v: T, f: fn(T): T): T {
    return f(f(v));
}

assert(twice(2, (n: Int) => n + 3) == 8, "generic closure");
assert(twice("ab", (s: String) => s + "!") == "ab!!", "generic string");

The default erases type parameters to Any. To get native functions with concrete signatures instead, list the concrete types with #[Monomorph(...)]. Each entry produces one function with a deterministic suffix: Int becomes I32, Float becomes F64.

.rnx
#[Monomorph(Int, Float)]
fn scale<T>(value: T, by: T): T {
    return value * by;
}

assert(scaleI32(6, 7) == 42, "integer monomorph");
assert(scaleF64(1.5, 2.0) == 3.0, "float monomorph");

A monomorphized call resolves trait methods on the concrete type through the normal class and extension rules. The attribute must list a whole number of type-tuples matching the function's type parameters; a mismatch fails with E108. Call the generated name directly, since call-site inference for these functions is not implemented.

Closures capture this strongly by default, like any other value. A closure stored on its own object requires fn decay(this), the weak opt-in; see Cycles and Handles.

Trailing blocks

A block after a call is a child list, not a callback. The call runs first, then each expression statement in the block is passed to addChild on the result, and the result is the value of the whole expression:

.rnx
Column {
    Text("Count: 3")
    Button("Add", onTap: () => count += 1)
}

let is scoped to the block. if, for, and switch flatten, so the statements in the taken branch or the loop body become children in source order. The callee's type must provide addChild, or the block is an E108 naming that type. Handlers stay named parameters, which is what keeps the block unambiguous.

Methods

Functions defined inside a class or struct take an implicit receiver and call with dot syntax. Inside the body, this refers to the receiver. init(params) runs at construction (new Meter(20) calls it; .init() is never written). static methods call on the type itself with no receiver.

.rnx
class Meter {
    let reading: Int;

    init(reading: Int) {
        this.reading = reading;
    }

    fn bump(amount: Int): Int {
        this.reading = this.reading + amount;
        return this.reading;
    }
}

let m = new Meter(20);
println!(m.bump(22));

throws and try..catch

A function that can fail marks throws, bare, with no error set. Callers are inside try or declare throws themselves; the checker enforces the contract. throw carries any value. A bare throw; rethrows the current error and is legal only directly inside catch.

.rnx
fn load(ok: Bool): Int throws {
    if ok { return 42; }
    throw 0;
}

try {
    println!(load(true));
} catch (err) {
    println!("failed");
}

Calling a throws function from another function propagates on every backend through a per-thread error slot; the nearest enclosing catch receives the payload.

try accepts an optional single catch (id) plus an optional finally. The finally block runs on normal exit, error return, and nested rethrow alike; it desugars to a synthetic defer and shares those exact semantics. defer blocks registered between a throw and its catch run first, innermost first.

.rnx
fn Main(): Int {
    let log: Array<String> = [];
    try {
        defer log.push("inner");
        throw "down";
    } catch (err) {
        log.push("caught: " + err);
    }
    println!(log[0]);
    println!(log[1]);
    return 0;
}

A throw propagates on every backend, across function boundaries, through a per-thread error slot. Thrown class instances keep their identity: is checks match (including ancestors) and narrow the binding, so fields are accessible in the arm. An error that escapes all handlers fails the entry call. switch over the caught value with case is Type: arms dispatches the same way.

.rnx
class IoError {
    let message: String;
    init(message: String) { this.message = message; }
}

class ParseError {
    let message: String;
    init(message: String) { this.message = message; }
}

fn first(): String throws {
    throw new ParseError("bad header");
}

fn Main(): Int {
    try {
        println!(first());
    } catch (err) {
        switch err {
            case is IoError:
                println!("caught io");
                pass;
            case is ParseError:
                println!("caught parse");
                pass;
            default:
                println!("caught other");
                pass;
        }
    }
    return 0;
}

Functions that cannot usefully decide an error declare throws and propagate; handling belongs at the boundary where retry, default, or abort-with-context is available.

Nullable and Result channels: ? ?? ?.

Result values unwrap with postfix ?. Ok yields the payload; Err returns early carrying the error, so the enclosing function must return a Result. ? binds tighter than binary operators and never steals ternary colons. Applying ? to a non-Result value, or inside a function returning something else, is a compile error.

.rnx
fn popIt(): Result<Int, String> {
    let arr = [10, 20];
    let v = arr.pop() ?? -1;
    return Result.Ok(v + 1);
}

println!(popIt().unwrap());

lhs ?? rhs yields lhs when it is not null and evaluates rhs otherwise; rhs never runs when lhs is present. Either side may be nullable, so fallbacks chain.

.rnx
let port: Int? = null;
assert((port ?? 8080) == 8080, "fallback");
let a: Int? = null;
let b: Int? = 42;
assert((a ?? b ?? 8080) == 42, "chain");

target?.field and target?.method(args) short-circuit a chain: a null anywhere yields null without touching the rest. ?. must directly touch its operands.

.rnx
record Profile(name: String)
record User(profile: Profile?)

let user = User(Profile("Al"));
assert(user?.profile?.name == "Al", "chain");
let ghost = User(null);
assert((ghost?.profile?.name ?? "anonymous") == "anonymous", "fallback");

Test functions

Functions marked test fn take no parameters, return nothing, and are stripped from normal builds. The test runner discovers them, times them, and reports each one. assert takes a Bool and a message. Test execution is specified in Project and Toolchain.

.rnx
test fn addsUp() {
    assert(1 + 1 == 2, "math");
}

async and await

async fn names cooperative work; await suspends until it settles. This is the one place the language suspends rather than blocks. Compare Thread.spawn plus join(), which blocks the calling thread (see Concurrency and Threads).

ItemSignatureMeaning
async fnasync fn name(params): T { ... }returns Promise<T>; body runs cooperatively
awaitawait expr: Promise<T>: Tparks at 0% CPU until settled, resumes with the value; rejection propagates
.wait()promise.wait(): Result<T, String>blocking bridge for synchronous callers
Promise.resolve(v)Promise.resolve<T>(v: T): Promise<T>already-settled promise
.rnx
async fn compute(): Int {
    return 41 + 1;
}

let result = await compute();
assert(result == 42, "await value");

Rules: await outside an async fn is an E109 error, except at the top level of the entry file where it just works. Direct .poll() calls are an E111 error: the polling model is retired. Main itself may be async; the compiler uses the resolved value as the exit code. From synchronous code, bridge with .wait().unwrap() instead of await.

.rnx
async fn fetch(): Int {
    return 7;
}

fn Main(): Int {
    let v = fetch().wait().unwrap();
    assert(v == 7, "bridge");
    return 0;
}

Call and failure reference

Call shapeMeaningError when wrong
f(a, b)positional arguments, left to rightarity or type mismatch: E108 with the parameter named
f(x, name: v)named arguments after positionalsunknown or duplicate name: E108
f<T>(v)explicit type argumentinference conflict names the parameter: E108
throws caller outside trypropagation requires try or own throwschecker rejects: E108
bare throw; outside catchrethrow current errorlegal only directly inside catch: E108 otherwise
postfix ? on non-Resultearly-return through Result onlyE108
? inside non-Result functionenclosing function must return ResultE108

Summary

  • fn name(params): Ret with block bodies and return; (params) => body lambdas capturing by value.
  • Trailing defaults with positional-or-named calls; generics solved per call.
  • Methods use this; init constructs; static needs no receiver.
  • throws marks fallibility; try/catch/finally handle; throw carries values.
  • ? early-returns through Result; ?? falls back; ?. reaches through.
  • test fn marks tests; mismatched returns are E304.