Types and nullability#

Meta: nullability is the page's main attraction. Most readers won't have seen GraphQL-style T! outside of a schema and may misread it as "definitely-null" or "force-unwrap."

Dang's types follow GraphQL: every type is nullable unless it ends in !. The type checker tracks which values may be null and makes you deal with them before you use them.

The examples on this page are live: they share one Dang environment, so later snippets use earlier definitions. Each result is computed and baked in by the docs build — edit a snippet and hit Run ▶ to replay the page in your browser. Blocks that show an error are supposed to fail: the build verifies the failure the same way it verifies the results.

Built-in types#

The ! sigil#

T! is a non-null T. Plain T is nullable: it holds a T or null.

let nickname: String = null

nickname
=> null

A T! can go anywhere a T is expected, but not the other way around. A String may be null, so it can't fill a String!:

let display: String! = nickname
Type error: cannot use String as String!

! applies to the type just before it, so list types read from the inside out: [String!]! is a non-null list of non-null strings. A constructor call or a record literal always gives a non-null value.

Lists, nullability matrix#

written meaning
[T] nullable list of nullable T
[T]! non-null list of nullable T
[T!] nullable list of non-null T
[T!]! non-null list of non-null T

A list literal with a null in it is a [T]!, so it doesn't fit a list of non-null elements:

let scores: [Int!]! = [10, null, 30]
Type error: cannot use [Int]! as [Int!]!

Null propagation#

Reading a field through a nullable value gives a nullable result, even if the field itself is non-null. A chain stops at the first null link:

type User {
  name: String!
  nickname: String
  manager: User
}

let ada = User(name: "Ada", manager: User(name: "Grace"))

[ada.manager.name, ada.manager.manager.name]
=> ["Grace", null]

Operators are the exception. Arithmetic and ordering need non-null operands, so a nullable operand is a type error, not a null result (see Operators):

let scores = [10, null, 30]
scores[0] + 1
Type error: operator addition is not defined for nullable type Int: supply a default with ??, assert it with !, or bind it to a local with let and check that for null

To get a non-null value back, give a default with ?? (see Operators), or check for null and let narrowing do the rest (next section):

ada.nickname ?? ada.name
=> "Ada"

Function values can be null too: an element of a list of functions, a method taken off a nullable value (&h.hook), an if without else. Such a value can't be called until you check it for null, assert it with !, or give it a default with ??:

increment(x: Int!): Int! { x + 1 }
square(x: Int!): Int! { x * x }

let steps = [&increment, &square]
steps[0](5)
Type error: cannot call steps[0]: it may be null (((x: Int!): Int!)?); bind it to a local with let and check that for null, or assert it with ! (`…!(…)`)
[steps[0]!(5), steps[1]!(5)]
=> [6, 25]

Calling a method through a nullable value (h.hook(1)) still just propagates the null.

Flow-sensitive narrowing#

Meta: this section pays for itself — the alternative is writing ! casts everywhere. Make sure the examples include both narrowing inside a branch and narrowing after a guard clause.

Null narrowing#

Checking a name against null narrows its type. After a guard that leaves early, the name is non-null for the rest of the scope:

greet(name: String): String! {
  if (name == null) { return "hello, stranger" }
  `hello, ${name.toUpper}`
}

[greet("ada"), greet(null)]
=> ["hello, ADA", "hello, stranger"]

Inside a branch, the check narrows just that branch. Here count is an Int! in the then-branch, and the if has no else, so double returns Int:

double(count: Int): Int {
  if (count != null) { count * 2 }
}

[double(4), double(null)]
=> [8, null]

The else branch of an == null check is narrowed the same way:

excited(name: String): String! {
  if (name == null) { "nobody" } else { name + "!" }
}

excited("Grace")
=> "Grace!"

A guard that breaks narrows the rest of a loop body. This walks a linked list until it runs out:

type Link { value: Int!; next: Link }

let cur: Link = Link(1, Link(2, Link(3)))
let sum = 0
loop {
  if (cur == null) { break }
  sum += cur.value
  cur = cur.next
}

sum
=> 6

cur is declared as a Link so it can hold the null at the end. A mutable binding keeps the type of its first value, so let cur = Link(1) would make it a Link!, and the null from cur.next wouldn't fit.

Diverging constructs are narrowing-aware#

return, raise, break, and continue all leave the current path. When a guard's then-branch does one of them, the code after the guard knows the check was false:

At the top level of a script, a guard narrows the statements after it, but not declarations. Every let and function runs before the first statement, so the let below runs before the guard does:

let input = "hello" :: String
if (input == null) { raise "missing input" }
let loud: String! = input.toUpper
Type error: cannot use String as String!

case clauses narrow too. A clause runs only when the clauses before it didn't match, so after a null => clause the operand is non-null. This works when the operand is a bare name:

describe(n: Int): String! {
  case (n) {
    null => "nothing"
    0 => "zero"
    else => `${n + 1} comes next`
  }
}

[describe(null), describe(0), describe(4)]
=> ["nothing", "zero", "5 comes next"]

The same goes for the conditions of a case without an operand:

size(n: Int): String! {
  case {
    n == null => "unknown"
    n > 100 => "big"
    else => "small"
  }
}

[size(null), size(500), size(7)]
=> ["unknown", "big", "small"]

Reassigning a narrowed name#

A narrowed name can still be assigned anything its declared type allows. A non-null value keeps it narrowed. A value that may be null ends the narrowing until the next check:

secondValue(list: Link): Int! {
  let cur = list
  if (cur == null) { return 0 }
  cur = cur.next
  cur.value + 1
}
Type error: operator addition is not defined for nullable type Int: supply a default with ??, assert it with !, or bind it to a local with let and check that for null

The same goes for writes the checker sees less directly:

Here reset sets total back to null, so calling it ends the narrowing:

tally: Int! {
  let total: Int = 1
  reset: Int! { total = null; 0 }
  if (total == null) { return 0 }
  reset
  total + 1
}
Type error: operator addition is not defined for nullable type Int: check it for null first, supply a default with ??, or assert it with !

Writes a read can't follow from don't count: those in the other branch of the same if or another arm of the same case, in a branch that returns (or, for the rest of a loop body, breaks or continues), or in a nested function that isn't called. A branch's exit doesn't hide its writes inside a rescue operand or a block passed to a Dang function, though: a raise before the exit may be rescued.

Type narrowing via case#

A binding: Type! => clause binds the operand narrowed to that type, which is non-null: null matches no type pattern. This is how you take apart a union, such as the one an if/else with unrelated branches produces:

type Cat { name: String! }
type Dog { name: String!; tricks: [String!]! = [] }

let pet = if (sum > 5) Dog(name: "Rex", tricks: ["sit"]) else Cat(name: "Tom")

case (pet) {
  c: Cat! => `${c.name} ignores you`
  d: Dog! => `${d.name} can ${d.tricks.join(" and ")}`
}
=> "Rex can sit"

rescue clauses use the same form, so a typed rescue clause narrows the error it binds (see Errors: raise and rescue).

Conditional result inference (related)#

An if with a null branch, or with no else, has a nullable type. Branches of unrelated types widen to their common interface, or to a union (like pet above). Either way, the type only matters once you use the result. Here label is a nullable String:

let label = if (sum > 5) "many" else null
label + "!"
Type error: operator addition is not defined for nullable type String: check it for null first, supply a default with ??, or assert it with !

Compound conditions#

An or guard that leaves early narrows both names, because getting past it means both checks were false:

add(a: Int, b: Int): Int! {
  if (a == null or b == null) { raise "missing an operand" }
  a + b
}

add(1, 2)
=> 3

An and condition narrows both names inside the then-branch:

multiply(a: Int, b: Int): Int {
  if (a != null and b != null) { a * b }
}

[multiply(2, 3), multiply(2, null)]
=> [6, null]

The right side of and sees the left side's narrowing, and the right side of or sees the opposite, so a guard works inline:

isPositive(n: Int): Boolean! { n != null and n > 0 }

[isPositive(3), isPositive(null), isPositive(-1)]
=> [true, false, false]

Limitations#

Narrowing is local to one function: calling another function doesn't carry narrowed types across.

An and guard that leaves early does not narrow. Getting past it only means at least one name is non-null, so neither is narrowed:

sumBoth(a: Int, b: Int): Int! {
  if (a == null and b == null) { raise "both missing" }
  a + b
}
Type error: operator addition is not defined for nullable type Int: check it for null first, supply a default with ??, or assert it with !

Field reads don't narrow. Each .field read could return a different value, so checking user.nickname says nothing about the next read:

loudNickname(user: User!): String! {
  if (user.nickname == null) { return user.name }
  user.nickname.toUpper
}
Type error: return type mismatch: declared String!, inferred String

Bind the field to a local first, and check that:

loudNickname(user: User!): String! {
  let nick = user.nickname
  if (nick == null) { return user.name }
  nick.toUpper
}

loudNickname(User(name: "Ada", nickname: "countess"))
=> "COUNTESS"

The same applies to a computed member (title: String { … }) read by its bare name: each read calls it again. Narrowing does work on locals, parameters, and a method's bare reads of its own stored fields.

When narrowing can't reach the value — a field or call result, or a spot where the checker just can't follow your reasoning — the postfix ! operator is the explicit escape hatch: expr! narrows T to T! and raises at runtime if the value turns out to be null. See Operators.

ada.manager!.name
=> "Grace"

See also Errors: raise and rescue (raise/rescue divergence) and Control flow (guards, loops, case).

Meta: field-narrowing and the and-guard non-narrowing are the two most surprising gaps in practice. Both are documented above with the re-bind-to-a-local workaround.

Type variables#

A single lowercase letter (a, b) in a signature is a type variable. It stands for whatever type the caller passes, and is inferred at each call:

pair(x: a): [a]! { [x, x] }

[pair(1), pair(2)]
=> [[1, 1], [2, 2]]
pair("hi")
=> ["hi", "hi"]

A type variable is opaque. The function can pass the value along, return it, or compare it with == and !=, but nothing else:

doubled(x: a): a { x * 2 }
Type error: operator multiplication is not defined for the generic type a: a type variable supports no operations; declare it `[a: Numeric]` to use it

Use a concrete type (here Int!) if the body needs to operate on the value, or bound the type variable: by Ordered to compare values, by Numeric to do arithmetic on them.

Type parameters, Ordered and Numeric#

A function or method may list its type parameters after its name. Without the list they are implicit, as above; with it, the list must declare every type variable the signature uses, each once, and use every one it declares:

second[a, b](x: a!, y: b!): b! { y }

second(1, "two")
=> "two"

A parameter may be bounded by Ordered, the types whose values have an order: Int!, Float!, String!, Boolean!, enums (in declaration order), custom scalars, and lists and {{ }} records of those, compared element by element. These are exactly what <, >, <= and >= compare and what .sort and .sortBy order (see Collections). In the body, values of a bounded a! compare, and the function can pass them on to another Ordered-bounded one:

insert[a: Ordered](xs: [a!]!, x: a!): [a!]! {
  xs.takeWhile { y => y <= x } + [x] + xs.dropWhile { y => y <= x }
}

insertionSort[a: Ordered](xs: [a!]!): [a!]! {
  xs.reduce([]) { acc, x => insert(acc, x) }
}

{{ints: insertionSort([3, 1, 2]), lists: insertionSort([[2], [1, 9]])}}
=> {{ints: [1, 2, 3], lists: [[1, 9], [2]]}}

The bound is on the type, not its nullability: a: Ordered stands for T or T! for any Ordered T!, so write a! for the values you compare. A bare a may be null, and < refuses it.

Each call checks the bound where the type is supplied, so a key with no order is an error at the block returning it:

mySortBy[a, k: Ordered](xs: [a!]!, &key(item: a!): k!): [a!]! {
  xs.sortBy { x => key(x) }
}

type Point {
  x: Int!
}
mySortBy([Point(2), Point(1)]) { p => p.x }.map { p => p.x }
=> [1, 2]
mySortBy([Point(2), Point(1)]) { p => p }
Type error: block argument: cannot use Point! for `k: Ordered`: it has no order; Ordered types are Int!, Float!, String!, Boolean!, enums, scalars, and lists and {{ }} records of those

A call that leaves the type unknown (insertionSort([])) keeps the bound on it until something learns the type, and checks it there. Inside a generic body, an unbounded type variable has no order, and comparing its values is an error that says to declare the bound:

smaller[a](x: a!, y: a!): a! {
  if (x < y) { x } else { y }
}
Type error: operator less_than is not defined for the generic type a: a type variable supports no operations; declare it `[a: Ordered]` to use it

Ordered is a constraint, not a type: x: Ordered! is an error.

The other bound is Numeric: the number types, Int! and Float!. Values of a Numeric-bounded a! take +, -, *, /, % and unary -, so you can write your own folds:

mySum[a: Numeric](xs: [a!]!, zero: a!): a! {
  xs.reduce(zero) { acc, x => acc + x }
}

{{ints: mySum([1, 2, 3], 0), floats: mySum([0.5, 0.25], 0.0)}}
=> {{ints: 6, floats: 0.75}}

The result follows the numbers, as it does without a type variable: a! with a! or with an Int! is a! (Int with Int stays Int, so / divides Ints), and anything with a Float! is Float!:

mean[a: Numeric](xs: [a!]!): Float! {
  xs.reduce(0.0) { acc, x => acc + x } / xs.length
}

mean([1, 2])
=> 1.5

Only the numeric + applies — a Numeric value doesn't concatenate with a string — and two different Numeric parameters don't mix, since one might be an Int and the other a Float. An unbounded variable's arithmetic is an error that says to declare the bound:

plus[a](x: a!, y: a!): a! { x + y }
Type error: operator addition is not defined for the generic type a: a type variable supports no operations; declare it `[a: Numeric]` to use it

Bounds combine with &: [a: Ordered & Numeric] both compares and adds, and compares with number literals the way it adds with them:

abs[a: Ordered & Numeric](x: a!): a! {
  if (x < 0) { -x } else { x }
}

{{int: abs(-3), float: abs(-2.5)}}
=> {{int: 3, float: 2.5}}

.sum on lists is bounded by Numeric (see Collections). An interface method declares type parameters and bounds the same way (see Interfaces and unions).

Type hints / casts: ::#

expr :: Type gives an expression a type. It binds only a single term on its left, so wrap anything bigger in parentheses: (a + b) :: Int! (see Operators for precedence).

As a hint, it fills in a type the checker can't infer, such as the element type of an empty list:

let tags = [] :: [String!]!
tags.length
=> 0

As a cast, it converts a String into a custom scalar or an enum. This is how a value that isn't a literal becomes one (see Enums and scalars):

scalar URL

let host = "example.com"
let site = `https://${host}` :: URL!
site
=> "https://example.com"
enum Plan { FREE PRO }

let plan = "PRO" :: Plan!
plan == Plan.PRO
=> true

Only String values convert to an enum; String values and values of another custom scalar convert to a custom scalar. Anything else is rejected before the script runs:

42 :: URL!
Type error: type hint mismatch: expression has type Int!, but hint expects URL!

A string literal cast to an enum is checked before the script runs, too. A string that isn't a literal is checked when the cast runs:

"ENTERPRISE" :: Plan!
Type error: "ENTERPRISE" is not a value of Plan; expected one of FREE, PRO
let wanted = "ENTERPRISE"
wanted :: Plan!
Runtime error: invalid enum value "ENTERPRISE" for Plan

Casting a nullable value to a non-null type is a runtime check, not a promise: it raises if the value is null.

JSON.decode("null") :: String!
Runtime error: null is not allowed for String!

Meta: :: deserves a worked example showing the difference between a type hint (narrowing/disambiguation, e.g. [] :: [String!]! binding a type variable) and a type cast (coercion, e.g. myUrl :: URL!). The runtime-assertion behavior for non-null casts is a footgun worth a short callout.

Coercion rules#

Passing a value to a parameter or a typed slot doesn't convert it. A String! variable doesn't fit where a URL! is expected:

fetch(url: URL!): String! { `GET ${url}` }

let address = "https://example.com"
fetch(address)
Type error: argument "url": cannot use String! as URL!

The exception is a literal: a string literal, a template, or a list or map literal of them converts to a compatible scalar wherever a value is handed over — call arguments, typed slots, and return values:

[fetch("https://example.com"), fetch(`https://${host}/docs`)]
=> ["GET https://example.com", "GET https://example.com/docs"]

For any other value, cast with :: (see above):

fetch(address :: URL!)
=> "GET https://example.com"

List literals don't convert their elements to match each other. One ID! element doesn't turn the plain string next to it into an ID!:

["abc" :: ID!, "def"]
Type error: unify index 1: no common type between String! and ID!