Types
Hot is gradually typed. Add annotations where they help catch errors and
document intent; skip them where they add noise. Hot infers types when it has
enough information and uses Any when a value's type or shape cannot be
established statically.
The model is deliberately hybrid:
- Plain records are checked structurally when their fields are known.
- Constructed types and enum variants retain nominal runtime tags.
- Literal and union types narrow the accepted values.
Anyis the dynamic escape hatch at partially typed boundaries.
Built-in Types
| Type | Description | Example |
|---|---|---|
Str | Text strings | "hello", `template`, """block""", ```block template``` |
Int | Integers | 42 |
Dec | Decimal numbers | 19.99 |
Bool | Booleans | true, false |
Null | Null value | null |
Vec | Vectors (also known as arrays) | [1, 2, 3] |
Map | Maps (objects) | {a: 1} |
Fn | Functions | (x) { x } |
Any | Any type | anything |
Bytes | Binary data | — |
Byte | Single byte (0–255) | — |
Result | Success (Ok) or error (Err) wrapper | ok(42), err("bad") |
Numbers
An Int is a 64-bit integer, from -9223372036854775808 to
9223372036854775807. Arithmetic whose result doesn't fit in an Int returns
Err("Integer overflow"), as dividing by zero returns
Err("Division by zero"). A Dec is an exact 256-bit decimal, so
add(0.1, 0.2) is 0.3. Mixing an Int and a Dec gives a Dec.
Type Annotations
Add types to variables:
name: Str "Alice"
count: Int 42
prices: Vec<Dec> [9.99, 19.99]
Add types to function parameters and returns:
greet-typed fn (name: Str): Str {
`Hello, ${name}!`
}
process fn (items: Vec<Int>, multiplier: Int): Vec<Int> {
map(items, (x) { mul(x, multiplier) })
}
greet-typed("World") → "Hello, World!"
process([1, 2, 3], 2) → [2, 4, 6]
Types are Optional
You can skip types entirely:
// No types - still valid Hot
name-simple "Alice"
greet-simple fn (name) { `Hello, ${name}!` }
Hot will infer types where possible and allow Any elsewhere.
This is best-effort static checking rather than whole-program proof. A known
record can be checked against a required field shape, while an untyped
Map<Any, Any> may be accepted and fail later when code accesses a missing
field. Add annotations at API, storage, event, and other trust boundaries when
you want stronger diagnostics.
Generic Types
Parameterize collection types:
names-generic: Vec<Str> ["Alice", "Bob"]
counts-generic: Map<Str, Int> {apples: 5, oranges: 3}
matrix-generic: Vec<Vec<Int>> [[1, 2], [3, 4]]
Union Types
A value can be one of several types:
parse-number fn (input: Str): Int | Dec | Null {
// Returns Int, Dec, or null
}
process fn (value: Str | Int): Str {
Str(value)
}
Literal Unions
Union types can include literal values:
// String literals
Fruit type "apple" | "banana" | "orange"
// Number literals
DiceRoll type 1 | 2 | 3 | 4 | 5 | 6
// Mixed literals
Status type "pending" | "active" | 0 | 1
// Use in functions
pick-fruit fn (fruit: Fruit): Str {
`You picked a ${fruit}!`
}
apple: Fruit "apple" // Valid
pick-fruit("banana") // Valid
pick-fruit("grape") // constraint-violation: not a Fruit
Literal unions let you restrict values to a specific set of allowed values. A
literal outside a closed union, as in pick-fruit("grape"), is a compile-time
constraint-violation error from hot check. A closed union is checked at
runtime too: a computed value from outside the set, such as one parsed from
JSON, fails where it enters the type with Err(ConstraintError.Violation). An
open union also accepts unknown values of the same type. Literal union values
stay plain values, with no type tag. A union can name other literal unions, as
in Day type Weekday | Weekend or Workday type Weekday | "holiday": its
values stay plain too, and a match arm or is-type on it accepts a member of
any of them. See Constraints.
They also work inline, without a named type:
set-speed fn (mode: "fast" | "slow", retries: 0 | 1 | 3, note: Str | null): Str {
`Running ${mode} with ${retries} retries`
}
set-speed("fast", 3, null) // "Running fast with 3 retries"
Name the type when you reuse it or extend it with open.
Open Literal Unions
Declare a literal union open when more values will be added later. Each
later type open declaration of the same name adds members:
// Declare the union as open
Fruit type open "apple" | "banana" | "orange"
// Extend it. The leading `|` is optional
Fruit type open | "kiwi"
Fruit type open "mango" | "pineapple"
kiwi: Fruit "kiwi" // Valid: added by an extension
Extensions go at namespace top level. Repeating a member is allowed and
changes nothing. A literal outside the known values, such as "grape" here,
is an unknown-literal warning from hot check and is accepted at run time.
A value of another type isn't: 5 fails where a Fruit is declared, at a
parameter, a field or inside a union such as Fruit | Bool.
A union is open or closed from its first declaration. Extending a closed
union with open, or declaring an open union again without it, is an
open-literal-union-mismatch error:
Size type "small" | "large"
Size type open | "medium" // open-literal-union-mismatch: Size is closed
Named Unions of Declared Types
A union can name records and enums: Order type Draft | Paid. It is the union
of its members. A Draft is an Order: is-type(draft, Order) is true, an
Order => arm matches it, and an (o: Order) overload takes it. Order(draft)
checks that draft is a member and returns it as it is, still a Draft, so a
Draft => arm still matches it. Given a Map, Order builds the one member the
Map fits, and fails when it fits none or more than one.
Constraints
Any type can carry a where clause, a predicate its values must pass:
Port type Int where between(%, 1, 65535)
listen fn (port: Port): Str {
`listening on ${port}`
}
A literal argument that fails, such as listen(70000), is a compile-time
constraint-violation error from hot check. A computed value that fails
becomes a Result.Err holding a ConstraintError at run time. See
Constraints for fields, invariants,
preconditions, and how checks run.
Nullable Types
Use ? for values that might be null:
find-user fn (id: Str): User? {
// Returns User or null
}
greet fn (name: Str, title: Str?): Str {
// title can be a Str or null
if(is-null(title), name, `${title} ${name}`)
}
Str? is shorthand for Str | Null.
Null isn't converted at a call. Null reaching a parameter declared without ? through an Any value fails at the call (see Parameter Checks). Only Str(null) and template interpolation turn null into "". Standard library functions return an Err for null unless their parameter is declared Str?: lowercase(null) fails, and is-empty(null) is true.
hot check warns with null-check-on-non-nullable on is-null(x) or is-some(x) for a parameter declared without ?. A literal null argument for one is a type-mismatch error at namespace top level, and a null-for-non-nullable warning inside a function body. Declare the parameter Str? when null is allowed.
Note: The
?syntax indicates the type accepts null—it does not make the parameter omittable. You must still pass an argument (either a value ornull). For truly optional parameters, use function overloading.
Why no
Optiontype? Languages without null (like Rust) useOption<T>withSome(value)andNoneto represent optional values. Hot has null to align with JavaScript/JSON data types, soT?achieves the same thing more concisely. WhileOptioncan technically express one extra state (Some(null)vsNone), this distinction is rarely needed in practice and adds complexity for everyone. If anOptiontype is needed, you can define a custom type and make it core to your codebase.
Defining Custom Types
Struct Types
Define a type with fields:
Person type {
name: Str,
age: Int,
email: Str?
}
Types Are Constructors
The type name is also its constructor function:
Point type {
x: Int,
y: Int
}
// Create an instance - type name IS the constructor
alice-point Point({x: 10, y: 20})
alice-point.x → 10
alice-point.y → 20
Key Concept: In Hot, types are functions that return values of that type. When you define a type, you're also defining a constructor function with the same name. This unifies type definitions and value creation into a single concept.
Named Arguments
A record type's constructor takes its fields by name, or one Map:
Account type {
owner: Str,
plan: Str,
seats: Int?
}
// Name each field. A field that allows null can be left out.
team-account Account(owner: "Ada", plan: "team")
// The same value, built from a Map
map-account Account({owner: "Ada", plan: "team"})
team-account.owner → "Ada"
team-account.seats → null
eq(team-account, map-account) → true
- Name every field you pass, in any order. Positional arguments,
...spreads, and pipes can't be mixed in. - A field whose type allows
nullcan be left out. Every other field is required. - The compiler checks the names. A name that isn't a field or a missing required field is a
named-argumenterror, and a name given twice doesn't parse. The Map form checks required fields when it runs. - A
%in a field typedFnbecomes a lambda there. - Enum variants with a record payload take names too:
Shape.Circle(radius: 5.0). - On a type with custom constructors, named arguments go to the default constructor, as the Map form does. The custom constructors don't run, and
whereconstraints are still checked. - A type with a one-parameter constructor that takes a Map doesn't take named arguments: that constructor decides which keys it reads. Pass it the Map.
Field Checks
A record's constructor checks each field against its declared type, the way a function checks a parameter. Named arguments and the Map form are checked alike. This catches values hot check can't see, such as a field of parsed JSON, which is Any:
Server type { host: Str, port: Int }
body from-json("{\"host\": \"a.example\", \"port\": \"443\"}")
Server(body) // Err: constructor of `Server` at `port` expected Int, got Str
- Built-in types follow a parameter's rules. Numbers convert only when nothing is lost, null fails unless the type allows it, and a value of a declared type over a built-in one, such as
Meters(80)fromMeters type Int, is stored as the value it holds:80. - Unlike a parameter,
Vec<T>andMap<K, V>check their contents:Numbers type { values: Vec<Int> }refuses{values: [1, "x"]}, and the error namesvalues[1]. - A
Map<K, V>field checks its keys too. JSON keys are strings, so a key that spells a number takes that number whereKis numeric:{"1": 2}atMap<Int, Int>has the key1. Two keys that become one fail rather than losing an entry. - In a union,
Map<K, V>comes after any record member, so data that builds the record is that record, whatever the order of the union. - A field typed as a record or enum takes a value of that type, a Map to build it from, or whatever a constructor it declares takes. A variant that holds the field's record builds that record:
Holder(ask: Status.Open(ask))holds anAsk. Any other record or variant of another type fails unless an arrow such asPaid -> Draftconverts it; its fields aren't copied across. Any other value fails, null included unless the field allows it. - A Map at an enum field builds the one variant it fits. At a closed enum, a Map that fits no variant, or more than one, fails. An open enum can have variants this program doesn't know, so there the Map stays as it is, for a
_arm. - A
Vec<T>orMap<K, V>of a record or enum treats each item or value as such a field:Album type { photos: Map<Str, Photo> }builds every value into aPhoto, and a value that can't be one fails. - A failure inside a nested record, or a
VecorMapof records, is reported from the outermost record, with the whole path:constructor ofOrderatitems[2].priceexpected Dec, got Str. - An
Errgiven for a field, or among the items or values of aVecorMapof records or enums, stops the construction and comes back as itself, unless the field isAny. - A field of a type declared over a built-in one, such as
Meters type Int, checks its value as that type and holds aMeters. - A type declared over a
VecorMapof records or enums builds what it holds the same way:Circles type Vec<Circle>builds every item into aCircle, andCircles([{radius: "x"}])fails at[0].radius. Awhererefinement of one builds them too, and its value stays a plainVecorMap. A parameter of such a type checks what it's given and doesn't build it. - Fields of type
AnyorFnaren't checked.
A failed check returns Err(ConstraintError.Violation), with the field in its path. A missing required field, or a value that no member of a union takes or more than one does, fails the same way: err-value(r).message reads the same for every refusal, and for a missing field names each one. A hand-written constructor's own Err stays as it wrote it, until a record holding it refuses: that's a Violation too, with the Err whole in its cause.
assoc, update, merge and deep-path assignment check the fields they write against their declared types, as the constructor does, and then the record's where constraints. The other fields aren't checked again, and a custom constructor doesn't run, so call it again if it should: Server(assoc(server, "port", value)).
Types over Built-in Types
A type declared over a built-in one holds a value of that type. Its constructor checks what it's given the way a field is checked, and tags the value with its own name:
Meters type Int
body from-json("{\"distance\": \"5\"}")
Meters(5) // Meters(5)
Meters(5.0) // Meters(5): the whole Dec converts
Meters(body.distance) // Err: constructor of `Meters` expected Int, got Str
Null fails unless the type allows it, as Note type Str? does, and Tags type Vec<Str> reads into its contents. A value of another type over a built-in one gives the value it holds, so Meters(Feet(3)) is Meters(3). A record or an enum variant isn't such a value and fails, even a variant carrying an Int. A type over Any takes any value and holds it as it's given, tags included; one over Fn takes any function. hot check reports a literal of the wrong kind, so Meters("x") fails before it runs.
Types with Custom Constructors
Add a constructor function for validation or convenience by combining the struct definition with a function:
// Struct definition + constructor function in single declaration
Point2D type {
x: Int,
y: Int
}
fn (x: Int, y: Int): Point2D {
Point2D({x: x, y: y})
}
Point2D(10, 20) → {x: 10, y: 20}
You can also define multiple constructor arities:
// Multiple constructor arities
Range type {
start: Int,
end: Int
}
fn
(end: Int): Range { Range({start: 0, end: end}) },
(start: Int, end: Int): Range { Range({start: start, end: end}) }
Range(10) → {start: 0, end: 10}
Range(5, 15) → {start: 5, end: 15}
A Map argument goes to the default constructor, which is how a custom constructor builds its value with Name({...}). A one-parameter constructor whose type takes a Map gets Maps instead. Its type can be Map, Map<K, V>, Map?, or a union with Map in any position:
Temp type {
celsius: Dec
}
fn (reading: Str | Map): Temp {
data if(is-str(reading), {celsius: Dec(reading)}, {celsius: reading.c})
Temp(data)
}
Temp("21.5").celsius // 21.5
Temp({c: 30.0}).celsius // 30.0
Inside the custom constructors, Temp({...}) still calls the default constructor, and so does Temp(data) in the constructor that takes Maps. If several constructors take a Map, one typed Map gets them before a union or nullable type.
A type declared over a built-in one keeps its default constructor for that type. With Label type Str and a constructor fn (n: Int): Label, Label("a") builds a Label, and Label(5) runs the custom constructor. A constructor of its own that takes a Str gets Strings instead. The constructors can follow on the next line, as after a record:
Label type Str
fn (n: Int): Label { Label(Str(n)) }
Label("a") // Label("a")
Label(5) // Label("5")
A constructor called with more arguments than any of its definitions takes fails rather than dropping the extra ones.
A record field or enum payload of such a type builds through the constructor that takes the value's type, as Temp(value) would. With temp: Temp, Reading({temp: "21.5"}) runs Temp("21.5"). That is how a ::hot::time/PlainDate field takes "2026-01-02", and a string that doesn't parse makes the record an Err. A value that no constructor takes by its type is an Err.
Types Inside Functions
A type declared inside a function body is local to that function, as a local
function is (see Functions Inside Functions).
It is a type of its own: a namespace type of the same name is a different type,
and code outside the function can't name it. Its values can still leave the
function. They print with the name Hot gives the type, such as ::app/Point@f
for Point declared in f.
In its function it works as a namespace type does: constraints are checked,
match arms can name it and its variants, and a separate Point type fn (...)
in the same block adds constructors to it. A constructor declared that way
can't read the function's variables. Arrows (A -> B) still belong at the top
of a namespace.
Empty Types (Markers)
Types with no fields work as markers or tags:
Token type {
}
Admin type {
}
token Token()
admin Admin()
Enums (Variant Unions)
Define a type with multiple named variants using the enum keyword:
// Simple variants (no data)
Direction enum {
Up,
Down,
Left,
Right
}
// Create values
up-dir Direction.Up
down-dir Direction.Down
Variants with Data
Variants can carry data by referencing other types:
// Define the payload types first
Circle type {
radius: Dec
}
Rectangle type {
width: Dec,
height: Dec
}
// Define the enum
Shape enum {
Point,
Circle(Circle),
Rectangle(Rectangle)
}
// Create values
shape-point Shape.Point
shape-circle Shape.Circle({radius: 5.0})
shape-rect Shape.Rectangle({width: 10.0, height: 20.0})
A payload can be any type expression, such as a built-in type, a list of records or an optional record. The variant checks its data the way a record field of that type is checked:
Ask type { key: Str }
Status enum { One(Ask), Many(Vec<Ask>), Maybe(Ask?), Done }
one Status.One(key: "a")
many Status.Many([Ask(key: "a"), {key: "b"}]) // each item is built as an Ask
none Status.Maybe(null)
A payload can also be a refinement or a literal union, named or written inline with where. The variant checks it as a record field of that type is checked, and the value stays plain:
Positive type Int where gt(%, 0)
Due enum { Hours(Positive), Days(Int where gt(%, 0)), Done }
Due.Hours(4) // Due.Hours(4)
Due.Days(n) // Err(ConstraintError.Violation) when n is 0
An enum's own where (Shape enum { ... } where ...) is checked when a variant is built, and updates of a variant's payload check the payload's type and the enum's where again.
Built-in Variant Types
Hot uses variant unions for core types:
// Result has Ok and Err variants
success Result.Ok(42)
failure Result.Err("Not found")
Enums from Other Namespaces
Name an enum from another namespace through an import of its type, or in full. Variants and payload types can be qualified wherever a variant is named:
::geo ns
Circle type { radius: Dec }
Shape enum { Circle(Circle), Dot }
::app ns
::g ::geo
b ::geo/Shape.Circle(radius: 2.0) // the variant in full
c ::g/Shape.Circle({radius: 3.0}) // through a namespace alias
d ::geo/Shape.Dot // a unit variant is its value
Circle ::geo/Shape.Circle // alias one variant
e Circle({radius: 4.0})
describe fn match (s: ::geo/Shape): Str {
::geo/Shape.Circle => { "circle" }
::geo/Shape.Dot => { "dot" }
}
Ring type { inner: Dec, outer: Dec }
Form enum { Round(::geo/Circle), Band(Ring) } // a qualified payload type
An import of any type (Port ::net/Port) stands for it wherever its full path
would: in an annotation, with is-type, and as a function value, as in
map-vals(settings, Port).
An alias of a variant with a payload is its constructor. An alias of a unit variant is the variant's value.
Type-Level and Variant-Level Matching
Use match to check variant types (preferred):
describe-direction fn (dir): Str {
match dir {
Direction.Up => "going up"
Direction.Down => "going down"
Direction.Left => "going left"
Direction.Right => "going right"
}
}
describe-direction(Direction.Up) // "going up"
describe-direction(Direction.Down) // "going down"
Matching a Variant's Payload
Inside an Enum.Variant arm, a binding the arm names (Reply.Declined (why))
holds that variant's payload: a Vec, a Str, an Int, and so on. The
matched name, including a fn match parameter, keeps the variant, so an arm
can pass it on as the enum. A record payload's binding keeps the variant too:
its fields read through to the payload. A unit variant has no payload:
Reply enum { Steps(Vec), Declined(Str), Sized(Circle), Pending }
summarize fn match (r: Reply): Str {
Reply.Steps (steps) => { `${length(steps)} steps` } // steps is the Vec
Reply.Declined (why) => { `declined: ${why}` } // why is the Str
Reply.Sized => { `radius ${r.radius}` } // r is the variant; fields read through
Reply.Pending => { "pending" }
}
// Without a binding, the matched name is the variant, so it passes on as the enum
keep-replies fn match (r: Reply): Reply {
Reply.Declined => { r }
_ => { Reply.Pending }
}
keep-replies(Reply.Declined("no budget")) // Reply.Declined("no budget")
summarize(Reply.Steps(["a", "b"])) // "2 steps"
summarize(Reply.Declined("no budget")) // "declined: no budget"
summarize(Reply.Sized({radius: 2.0})) // "radius 2.0"
A union arm (Reply.Steps | Reply.Declined =>) and a type-level arm
(Reply =>) keep the whole variant, since their payloads can differ.
A variant that holds a record reads as that record. With Status enum { Open(Ask) }, a parameter, return type, annotated binding or collection that
declares Ask takes a Status.Open as it is. The record's constraints are
checked, and the value stays the variant. The record's constructor builds the
record itself: Ask(status) is an Ask, and so is the field of
Holder(ask: status). An update such as assoc checks the value and keeps
the variant. is-type, a match arm and overload dispatch stay exact: a
Status.Open is a Status, never an Ask.
Using the matched name as the payload fails at run time or gives a wrong
value: length(r) counts the variant's own keys, and ${r} shows
::shop/Reply.Declined("no budget"). hot check warns with
variant-as-payload when the name reaches a place that takes the payload's
type but not the variant: a call's argument, a declared return type, an
annotated binding or a record field. It also warns when a template shows a
variant holding a scalar, and when eq or ne compares one with a literal
its payload could equal. Bind the payload in the arm to fix it.
Use is-type for dynamic type checking (see Type Checking).
Exhaustive Matching
match on a closed enum must cover every variant or fall through to a _
default arm. Union arms (A | B) count each variant they name, and an
Any arm covers everything. The compiler reports [non-exhaustive-match]
and lists the missing variants if none of these hold.
Direction enum { Up, Down, Left, Right }
// Exhaustive — every variant has an arm
travel fn match (d: Direction): Str {
Direction.Up => { "north" }
Direction.Down => { "south" }
Direction.Left => { "west" }
Direction.Right => { "east" }
}
// Also exhaustive — the union arm covers Up and Down, `_` catches the rest
classify fn match (d: Direction): Str {
Direction.Up | Direction.Down => { "vertical" }
_ => { "horizontal" }
}
The same rule applies to a match on a closed literal union, named or
inline: every member needs an arm, unless a _, Any, or type arm (such as
Str) covers the rest. A union arm counts each value it names. The error
lists the missing values. A nullable subject (Severity?) also needs a null
arm. An open literal union isn't checked this way, since other declarations
can add members.
Comparing a closed union's value with a literal outside it, as in
eq(severity, "hgih"), is always false (ne: always true), so hot check
warns with impossible-comparison. null and open unions aren't checked.
Naming a variant an enum doesn't have, as in a misspelled Direction.Upp,
makes hot check warn with unknown-variant: evaluating it fails at run
time. An arm such as Direction.Dwn => warns too, since it never matches.
A match on a nullable enum (Direction?) needs a null arm too, and one on
a union of declared types (Order type Draft | Paid) needs an arm for each
member, or a default.
Severity type "low" | "medium" | "high"
// [non-exhaustive-match]: missing arms for `"medium"`
rate fn match (s: Severity): Int {
"low" => { 1 }
"high" => { 3 }
}
Variants as Parameter Types
A parameter type can name one variant, in full if it's from another namespace. A sibling overload that declares the enum takes the other variants:
Circle type { radius: Dec }
Shape enum { Circle(Circle), Dot }
area fn
(s: Shape.Circle): Dec { mul(3.14159, mul(s.radius, s.radius)) },
(s: Shape): Dec { 0.0 }
radius fn (s: ::geo/Shape.Circle): Dec { s.radius }
Like other user types, it isn't checked at the call: a lone (s: Shape.Circle) still receives another variant as it is.
Open Enums
Add the open modifier to declare an extensible enum. Other modules add
new variants by declaring an arrow Source -> Enum.Variant. An open enum
with no seed variants is a pure extension point:
// Pure extension point — no initial variants
Plugin enum open { }
// Open enum with some seed variants
Animal enum open {
Dog,
Cat
}
Because the variant set of an open enum is unbounded, match on an open
enum must include a _ default arm — the compiler reports
[open-enum-match-missing-default] otherwise.
greet-animal fn match (a: Animal): Str {
Animal.Dog => { "woof" }
Animal.Cat => { "meow" }
_ => { "hello, friend" } // required for open enums
}
Arrow Enrollment
A single arrow declaration both enrolls a variant in an open enum and synthesizes its constructor. The bodyless form is the idiomatic shorthand:
Animal enum open { Dog, Cat }
Bird type { species: Str, wingspan: Dec }
Bird -> Animal.Bird // bodyless — wraps the source value as-is
eagle Animal.Bird({species: "Eagle", wingspan: 2.1})
The variant name does not need to match the source type name. This is a role-shaped variant, useful when a domain-specific tag reads better than the data type name:
Animal enum open { Dog, Cat }
Lizard type { length-cm: Dec }
Lizard -> Animal.Reptile // tag is Reptile, payload is Lizard
Declaring the same arrow twice — even from different files — is a
compile error ([ambiguous-type-implementation]) and the message points
to both source spans.
Type Coercion
Define how types convert to each other using ->:
Date type {
year: Int,
month: Int,
day: Int
}
// Define Date -> Str conversion (separate from type definition)
Date -> Str fn (date: Date): Str {
`${date.year}-${date.month}-${date.day}`
}
d Date({year: 2024, month: 12, day: 25})
Str(d) → "2024-12-25"
Multiple coercions:
Temperature type { celsius: Dec }
Temperature -> Str fn (temp: Temperature): Str {
`${temp.celsius}°C`
}
Temperature -> Int fn (temp: Temperature): Int {
round(temp.celsius)
}
temp Temperature({celsius: 23.7})
Str(temp) // "23.7°C"
Int(temp) // 24
Arrow declarations (Source -> Target) must live at the top level of a
namespace ([nested-type-implementation]). Arrows mutate the
global implementation registry, so a nested arrow inside a function body
would be a hidden global side effect — another part of the program could
pick up the implementation without ever seeing it referenced near where
it was declared. Local type definitions inside function bodies are
still allowed; the rule applies only to arrows.
Arrow coercions are one-hop. Hot does not search a chain such as
A -> B -> C to satisfy a parameter requiring C. If more than one direct
arrow could satisfy the same conversion, the call is ambiguous rather than
silently choosing one.
Arrows also apply implicitly when a call passes a value to a typed parameter,
if either side is a declared type: a Triangle passed to s: Shape goes through
Triangle -> Shape.Tri, and a Temperature passed to x: Str goes through
Temperature -> Str. An arrow between two built-in types doesn't apply
implicitly. Int -> Str backs Str(5), so f(5) for x: Str is a type error,
and a 5 that reaches x through an Any value fails at the call. Null is
never converted at a call. Named functions get arrows however they're called,
by map and other higher-order functions or through a variable. Lambdas don't
apply arrows.
Overloads take arrows into account. A Temperature passed to overloads
(x: Str) and (x: Vec) reaches (x: Str) through Temperature -> Str. An
overload that takes the value as it is comes first, and if arrows reach two
overloads that are equally good, neither is chosen for it.
Choosing an Overload
A call to overloads of the same arity runs the one whose parameters take its arguments best, by their values at run time. From best to worst, a parameter takes an argument:
- as a refinement or literal union the argument satisfies, as
(x: Pos)takes5before(x: Int)does, while-5goes to(x: Int); - as its own type, a variant at its enum included;
- as a member of a union or
?type, a record atMap, or a plainMapat a record type; - through a conversion: a value of a type over a built-in one at that built-in
type, an
IntatDecor a wholeDecatInt, or a plain value at a type over a built-in one that takes it; - as
Any; - through an arrow.
So (x: Int | Str) takes 1 before (x: Dec) does, and (x: Map) takes a
Map literal before (x: Point) does, while a Point goes to (x: Point).
A declared record, enum, variant or type over a built-in one takes no other
type's value, and a type of the same name from another namespace is another
type. A type declared only by constructors (Ship type fn (t: Str): Ship { Ship({tracking: t}) }) is a record with no declared fields, or a type over
Any when its constructors build it only from values that aren't Maps. A
named union takes each of its members. Function values, a core
function such as length or a var-imported one included, are Fn. A Result
parameter takes any value.
When no overload takes the arguments, an overload with a built-in parameter
type receives the call and refuses it with Err(ConstraintError.Violation),
as its parameter check does. When every overload names
declared types the arguments aren't, nothing checks them on entry, so the call
halts: No overload of `pair` with 2 parameter(s) accepts (Paid, Ship).
hot check makes the same choice when it knows the argument types, and reports
a call that no overload takes. It reads a refinement or literal union as the
type it refines, so where only a refinement separates two overloads, it
accepts the call and leaves the choice to run time: pos-or-int(-5) passes
the check and runs (x: Int). A literal is reported only when no overload of
the arity takes it. When an argument's type is unknown, such as a field of
parsed JSON, the call's result is Any unless every overload that could take
it returns the same type. When the overload it chooses declares a record,
enum or variant type, the call's result is that type, so a later call or pipe
stage is checked against it: Draft(...) |> apply(AddItem(25)) |> apply(Ship("1Z")) is reported, as the first stage returns a Draft.
hot check warns with ambiguous-overload at a call that overloads declaring
different types take equally well, such as (x: Int | Str) and (x: Int | Dec)
given an Int: the last one declared runs, so the choice rests on declaration
order. Declare the argument's own type in the overload that should run. It
warns with mixed-lazy-overloads when overloads of the same arity mark
different parameters lazy: a call evaluates its arguments for one of them,
so the other never runs, whatever the argument types.
Parameter Checks
A parameter annotated with a built-in type is checked when the function is
called, after any arrow has run. This catches values hot check can't see, such
as a field of parsed JSON, which is Any:
port-label fn (port: Int): Str { `port ${port}` }
body from-json("{\"port\": \"443\"}")
port-label(body.port) // Err: parameter `port` of `::app/port-label` expected Int, got Str
- The right type passes as it is. The check covers
Int,Dec,Str,Bool,Vec,Map,Bytes,ByteandNull, and unions and?forms of them. - Numbers convert only when nothing is lost: an
Intbecomes aDecatx: Dec, and a wholeDecsuch as443.0becomes anIntatx: Int.443.5and"443"fail atx: Int. Convert on purpose withInt(x). - Null fails unless the annotation allows it, as
x: Str?does. Vec<T>andMap<K, V>check the container, not its contents, so a call costs the same at any size. Use awhereconstraint to check the contents.- A value of a declared type over a built-in one, such as
Meters(80)fromMeters type Int, passesx: Intas the value it holds: the parameter receives80. The same goes for a refinement or literal union over a built-in type, a variadic parameter, a field and a variant's payload. A return value or binding is checked, and so unwrapped, only when its type is a refinement or literal union (: Pos); one declared: Intisn't checked when the program runs, soMeters(80)stays aMetersthere. An enum variant doesn't pass a built-in type, even one carrying anInt. - A record passes
x: Map. An enum variant, or a value of a type declared over a built-in one other thanMap, doesn't. - User types,
Any,Fnandlazyparameters aren't checked, and neither is the first parameter of afn matchwithResultarms, which holds theResult, whatever its annotation: the arms test it.
A failed check returns Err(ConstraintError.Violation) from the call, before the
body runs. Using that value halts as any Err does, but if, and, or and not
treat an Err as false, so use is-err where a bad value needs its own branch.
Comparing Values of Declared Types
gt, gte, lt, lte, between and sort read a value of a declared type over
a number as the number it holds:
Money type Dec
gt(Money(80.0), 100) // false
gt(Money(200.0), Money(80.0)) // true
sort([Money(200), Money(80.5)]) // [Money(80.5), Money(200)]
They go by the number alone, so gt(Money(200.0), Weight(80.0)) is true: comparing
two different types is yours to rule out. An enum variant isn't read this way, as
Temp.Celsius(30.0) is a case of its enum rather than a number.
gt, gte, lt, lte and between take numbers only, so gt("b", "a") is a
type-mismatch error from hot check. Strings are ordered by sort alone, which
reads a declared type over a string the same way.
hot check can't see inside an Any, such as a field of parsed JSON. Given two
strings that way, gt, gte, lt and lte order them at run time, and between
returns an Err. Don't build on the ordering: sort is the supported way to order
strings.
Arithmetic reads the number too, as any built-in parameter does, and returns a plain
number: add(Money(80.0), 1) is 81.0, a Dec, not a Money. Wrap the result
again, as in Money(add(m, 1)), to keep the type. Equality does not unwrap:
eq(Money(80.0), 80.0) is false, because the type is part of the value.
Values with no order give an Err, such as gt(1, null) or two vectors. As with
any Err, if reads that as false, so use is-err where a missing value needs its
own branch.
Result Types
Hot doesn't have exceptions. Instead, use Result for operations that can fail:
// Create results explicitly
success Result.Ok(42)
failure Result.Err("Not found")
// Using shorthand functions
success ok(42)
failure err("Not found")
// Check results
result safe-divide(10, 2)
if(is-ok(result),
`Result: ${result}`,
`Error: ${err-message(result)}`)
The Result type is an enum with Ok and Err variants:
Result enum {
Ok(Any),
Err(Any)
}
success Result.Ok(42)
`Value: ${success}` // "Value: 42" (auto-unwraps in templates)
Results automatically unwrap when used as function arguments: Ok values pass through, and Err values halt execution, unless the parameter is declared Result. This makes error propagation seamless.
See Error Handling for the full story on Result types, automatic unwrapping, and Result parameters.
Type Checking
hot check validates annotations, known record fields, call signatures,
exhaustive matches, and other statically visible constraints. It does not turn
Hot into a fully static language: Any, dynamically shaped maps, and values
from unresolved boundaries may defer failures until runtime.
A type name that nothing declares or imports is an unresolved-type error in
a parameter annotation, and an unresolved-type warning in a record field, a
variant's payload or a return annotation.
Among what it reports:
- A value constructed with a record's constructor is that type, not its
fields: a
Paiddoesn't pass where aDraftis declared, even with the same fields, unless an arrow converts it. A plain Map literal still passes for a record it fits. A type from another namespace with the same name is another type. - A constructor call is checked like a function call: the number of
arguments, each field's type in a Map or named arguments, a variant's
payload, and a custom constructor's own parameters.
Ship({to: 1})is atype-mismatchandShip("x", "y")anarity-mismatch. - A pipe stage checks the piped value against the first parameter, so
"abc" |> Meters()is an error, asMeters("abc")is. - A top-level binding read before the line that binds it is a
use-before-definitionerror, since top-level bindings run in order. Read it in a function, or bind it first. - A call is checked against the overload the VM would run; see Choosing an Overload.
- A
matchmust cover its subject, a union of declared types and a nullable enum included (see Exhaustive Matching), andarm-never-matchesandunhandled-errwarn about arms that never run or anErrno arm takes.
Structural compatibility and runtime identity answer different questions. A
known record may satisfy a struct parameter by supplying every required field,
while a value constructed with a type or enum constructor carries a nominal
tag used by match, is-type, serialization, and overload dispatch.
is-type and a match arm test a value as it is, without the conversions a
parameter makes: is-type(5.0, Pos) is false for Pos type Int where gt(%, 0),
and is-type(Meters(5), Int) is false, since a Meters is its own type.
Use is-* functions to check built-in types at runtime:
is-str(value) // true if Str
is-int(value) // true if Int
is-dec(value) // true if Dec
is-bool(value) // true if Bool
is-vec(value) // true if Vec
is-map(value) // true if Map, records included
is-bytes(value) // true if Bytes
is-fn(value) // true if function
is-null(value) // true if null
is-some(value) // true if not null
For custom types, use is-type:
Coord type {
x: Int,
y: Int
}
c Coord({x: 1, y: 2})
is-type(c, Coord) // true
is-type("hello", Coord) // false
The untype Function
Typed values carry internal metadata so Hot can preserve type identity at runtime. That wrapper is transparent to field access and is not a source-level reflection API: use normal field access, match, and is-type.
Collection functions see a typed value's fields too. get, get-in, keys, vals, and length read the fields. assoc, assoc-in, update, update-in, and merge return a value of the same type, like deep-path assignment, without re-running a custom constructor. Transforms such as map-vals, filter-keys, and delete, and map spread ({...server}), return plain maps of the fields.
to-json preserves that identity with Hot's tagged JSON representation, and
from-json restores it. Treat the tag as a wire format rather than constructing
or inspecting its metadata in Hot code. The serialized tag is an implementation
boundary, not an alternate source-level type-construction or reflection API.
Call untype before serialization when a recipient expects ordinary untagged
JSON:
// Define a type
Person type { name: Str, age: Int }
// Create a typed value
alice Person({name: "Alice", age: 30})
// Produce an untagged value
untype(alice) // {name: "Alice", age: 30}
When to Use untype
The most common use case is serializing typed data to JSON for HTTP requests:
// Tagged JSON is the default for typed values
to-json(alice)
// Untype explicitly requests ordinary untagged JSON
to-json(untype(alice)) // {"name":"Alice","age":30}
Use untype when calling external APIs that expect untagged JSON payloads:
// Sending typed data to an external API
request-body ChatRequest({
model: "gpt-4",
messages: [{role: "user", content: "Hello"}]
})
// Untype before converting to JSON
::hot::http/request("POST", url, headers, to-json(untype(request-body)))
Recursive Untyping
The untype function works recursively—it strips type metadata from nested types as well:
Order type { customer: Person, items: Vec<Item> }
order Order({
customer: Person({name: "Bob", age: 25}),
items: [Item({name: "Widget", price: 9.99})]
})
// Recursively removes all type metadata
untype(order)
// {customer: {name: "Bob", age: 25}, items: [{name: "Widget", price: 9.99}]}
Enums and untype
A plain value keeps a variant's name, so nothing is lost when it leaves Hot. A variant with no payload becomes its name, and a variant with a payload becomes a Map from its name to the payload:
Outcome enum { Passed, Failed }
Status enum { NotOwed(Str), Owed(Int) }
untype(Outcome.Passed) // "Passed"
untype(Status.NotOwed("no tax")) // {NotOwed: "no tax"}
untype(Status.Owed(5)) // {Owed: 5}
A record or variant field of an enum type reads this form back, so the constructor rebuilds what untype took apart. A name that isn't a variant of the enum is an Err:
Filing type { outcome: Outcome, status: Status }
filing Filing({outcome: Outcome.Passed, status: Status.Owed(5)})
plain untype(filing) // {outcome: "Passed", status: {Owed: 5}}
Filing(plain) // the same Filing
A Result isn't data of its own, so untype(ok(5)) is 5. To read a payload in code, use match or field access rather than untype.
Typed Values in the Store
::hot::store keeps a typed value as it is: put then get gives back the same record or variant, nested values included, and match and is-type work on it. Call untype first when something else reads the store and expects plain JSON, and rebuild the value with its constructor when you read it back.
Summary
- Types are optional — add them where they help
- Types are constructors:
Person(name: "Alice", age: 30)orPerson({name: "Alice", age: 30})creates a Person - Use
?for optional/nullable types:Str? - Use
|for union types:Int | Str - Use literal unions for exact value sets:
"apple" | "banana" - Use
wherefor constraints:Port type Int where between(%, 1, 65535) - Use enums (variant unions) for discriminated types:
Direction enum { Up, Down } - Define type coercions with
Type -> OtherType fn - Use
ResultwithResult.Ok()/Result.Err()instead of exceptions (see Error Handling) to-jsonpreserves typed values with tagged JSON; useuntypewhen the target expects untagged JSON