Errors and nullability
Kinmokusei separates expected operation failure, typed exceptional control flow, ordinary Go/runtime panics, and nullable references. Each path has distinct syntax and generated behavior.
For the decision-oriented chapter, read Failures, results, and exceptions.
import go fmt from "fmt";
import go strconv from "strconv";
class User {
constructor(public name: string) {}
}
function parsePositive(text: string): Result<int> {
const value = strconv.Atoi(text)?;
if (value < 0) {
return fail(fmt.Errorf("negative value: %d", value));
}
return ok(value);
}
function findUser(present: boolean): User | null {
if (present) { return new User("hello"); }
return null;
}
function describe(text: string, present: boolean): Result<string> {
const value = parsePositive(text)?;
const user = findUser(present);
if (user === null) { return ok("missing"); }
return string(fmt.Sprintf("%s:%d", user.name, value));
}
function main(): void {
const [description, err] = describe("21", true);
fmt.Println(description, err === nil);
}Expected output:
hello:21 trueResult<T> is a return effect
Result<T> lowers directly to (T, error); Result<void> lowers to error.
function parse(text: string): Result<int> {
const value = strconv.Atoi(text)?;
if (value < 0) { return fail(errors.New("negative value")); }
return ok(value);
}ok(value)returns success;ok()is theResult<void>form.fail(error)returns the result type's zero value plus the error.- Postfix
?evaluates once and immediately propagates a non-nil error. - Returning another Kinmokusei result of the identical type forwards it directly.
Result<T> is not a runtime wrapper. It cannot be stored in a variable, parameter, field, collection element, or nested result.
Function values returning Result<T> can be stored in those positions; the restriction applies to the effect itself, not the callable. Calling one still requires propagation, explicit splitting or matching return forwarding. An unused named source-Result error binding is a compile error. Use _ only when discarding failure is intentional:
const [value, err] = load() // Inspect, pass on or return err.
const [fallback, _] = load() // Explicitly discard failure.
const _ = load()? // Discard success but propagate failure.Whole-call _ = load() explicitly discards all results. These discard forms do not consume a Task; tasks still require await or detach. See handling and deliberate discard for the binding-use check and its limits.
Raw Go errors stay available
Direct Go calls expose their actual multiple results:
const [value, err] = strconv.Atoi(text);No implicit conversion hides the error. Postfix ? is the explicit bridge from a Go (T, error) operation or single error into an enclosing Result function. A non-void ? operation must initialize one binding; its control-flow boundary cannot be buried in an arbitrary expression.
Typed exceptions
try {
perform();
} catch (err: NotFoundException) {
recoverMissing(err.message);
} catch (err: Exception) {
recoverGeneral();
} finally {
cleanup();
}Exception is an extensible built-in class implementing Go's error contract. throw accepts an error value. Catch clauses are tested in source order; the checker rejects a specific type already covered by an earlier base, Exception, or error catch. Its message field and .error() text result are bstring, preserving raw Go error messages. Use checked string(err.message) when verified text is needed.
Bare throw; rethrows the currently handled exception. finally runs after normal completion, caught or rethrown Kinmokusei exceptions, return from try/catch, and ordinary Go/runtime panic. A return in finally replaces the earlier completion.
Only values carrying the explicit Kinmokusei exception marker enter catch dispatch. Bounds failures and arbitrary Go panics keep unwinding after finally.
An uncaught native exception terminates with a Go panic containing its original source class name and message, for example panic: NotFoundException: missing. The name is the constructed subclass, including after rethrow or a catch through a base type; generated module-link names are not used. Throwing an ordinary Go error displays its .Error() message. This panic display does not add a class prefix to Exception.message or .error(), which still return message text.
Nullable references
T | null marks a nil-backed reference as nullable. null belongs to this checked type system; imported raw Go nil retains its low-level Go meaning. The two do not assign implicitly.
Use const user: User | null = null for an absent source class. Development builds reject const user: User = nil, as well as raw nil initialization of source interfaces and function signatures. Aliases and generic bounds cannot bypass that rule. Go pointer/interface/callback types keep their raw Go nil behavior at the interop boundary.
const user = findUser(id);
if (user === null) { return "missing"; }
return user.name;Only nil-capable types can be nullable: classes, pointers, slices, maps, functions, channels and suitable interfaces. Scalars, fixed arrays, structs, structural object values, void and Result itself cannot.
A nullable function requires the same local narrowing as other references:
import go { Println } from "fmt"
alias Transform = (value: int) => int
function choose(enabled: boolean): Transform | null {
if (enabled) { return (value: int): int => value * 2 }
return null
}
const main = () => {
const transform = choose(true)
if (transform !== null) { Println(transform(21)) }
}This prints 42; calling the function before checking it against null would be rejected.
Member access, calls, indexing, slicing, pointer operations, and channel operations require a non-null proof. Operations that are explicitly safe on nil Go slices/maps—such as len, append, delete, clear, and range where applicable—retain that behavior.
When a Go API may return nil, choose an explicit nullable binding:
import go flag from "flag"
import go { Println } from "fmt"
function main(): void {
const flags = flag.NewFlagSet("example", flag.ContinueOnError)
const option: *flag.Flag | null = flags.Lookup("missing")
if (option === null) {
Println("missing")
return
}
Println(option.Name)
}Receiving a raw Go pointer or interface does not automatically prove it non-null. This example prints missing; accessing option.Name before the guard is rejected. An interface guard tests whether the interface itself is nil, not whether it contains a typed nil pointer. See Nullability.
? propagation from inside try still exits the enclosing Result function and runs finally; it is not a typed exception handled by catch. Handler flow checks include interrupted states, not just the normally completed try body. Bind getter results to locals before narrowing, because each property read can run different code and return a different value.
Flow facts and invalidation
v0.4.12 builds require presence checks for unsafe-zero payloads from ordinary [value, ok] map lookups, channel receives and as? assertions:
import go { Println } from "fmt"
class User {
constructor(public name: string) {}
}
function getOr<T>(values: Map<string, T>, key: string, fallback: T): T {
const [value, ok] = values[key]
if (!ok) { return fallback }
return value
}
function main(): void {
const users = makeMap<string, User>()
const user = users["missing"] ?? new User("guest")
Println(user.name)
const scores = makeMap<string, int>()
scores["known"] = 7
Println(getOr(scores, "known", 0))
Println(getOr(users, "missing", new User("fallback")).name)
}Check the matching local flag before reading, calling, returning or copying the payload. if (!ok) { return fallback; } is a useful early-exit form. Resetting the flag, using a copied/stale flag, or capturing mutable storage does not establish success. Nullable payloads still need a separate null guard even when the key exists. See zero values and absence.
To replace an absent reference, v0.4.12 provides lazy ??:
import go fmt from "fmt"
class User {
constructor(public name: string) {}
}
function main(): void {
let calls = 0
const find = (present: boolean): User | null => {
calls++
if (present) { return new User("金木犀") }
return null
}
const missing = find(false) ?? new User("fallback")
const found = find(true) ?? find(false)!
fmt.Println(missing.name, calls)
fmt.Println(found.name)
}This prints fallback 2 followed by 金木犀. The first lookup is absent, so the fallback runs; the second lookup returns a user, so the fallback is skipped. The source binding keeps its declared nullable type. A nullable fallback keeps the result nullable as well. See null coalescing for type context and Go interface behavior.
When null would be a programming error, use checked postfix !:
import go { Println } from "fmt"
class User {
constructor(public name: string) {}
}
function configuredUser(): User | null {
return new User("Kinmokusei")
}
function main(): void {
const user = configuredUser()!
Println(user.name)
}The operand runs once. A nil result causes a panic whose message identifies the source filename, line and column. The checked expression has type T, but the original binding remains T | null; bind the checked result if you want to use it repeatedly. Prefix !flag still means boolean negation. Do not use postfix ! for expected failure: it cannot unwrap Result<T> or a Task.
The declared type never changes. The checker maintains a separate fact for each program point:
let user: User | null = findUser();
if (user !== null) {
use(user.name); // proven non-null
user = null;
use(user.name); // rejected: assignment invalidated the proof
}Facts join conservatively across branches, switches, selects, and loop backedges. Address-taking, aliases, mutable closure capture, receiver reassignment, unknown calls, and reachable writes invalidate facts they may affect. A later check or non-null assignment can establish a new proof.
Closure bodies are checked separately from their enclosing flow. A mutable capture needs a check inside the closure, since it can change before invocation. An unreachable nested closure declaration does not contribute mutation effects to the enclosing flow, but the nested body still gets its own nullable and Task checks.
When storage is not stable, bind a snapshot:
const snapshot = this.currentUser;
if (snapshot !== null) { use(snapshot.name); }Invalid nullable access is covered by an intentionally failing documentation example; the docs check verifies that the compiler rejects it with the expected diagnostic fragment.
Runnable recipe
Parse input with Result shows a real Go (int, error) call, postfix propagation, application validation, success, and zero-value failure output.