Fields and functions#

Meta: introduce the field concept first and let the examples carry it — the whole rule is just: let makes a field local, a type makes it public, and a bare name = value reassigns. Then the four "feels weird at first" function points: zero-arity has no parens; the body has no return; positional args can mix with named; &fn is for references. Don't mention pub (it's legacy and formatted away). Object-context behavior lives in Objects (type) — link, don't duplicate.

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.

Fields#

A field is a named, typed thing — a value, a function, or a computed expression — declared in the current scope:

A field is recognized by its shape — a name followed by a type, an argument list, or a block body:

type Profile {
  name: String!                          # typed field
  greet: String! { `hi, ${name}!` }      # computed field / method
  plus(x: Int!): Int! { x + bonus }      # method with args
  bonus: Int! = 100                      # typed field with default
  nickname: String = null                # nullable
  let secret = "shhh"                    # local field (untyped is fine)
}

let ada = Profile(name: "Ada")

ada.greet
=> "hi, Ada!"

A field with no value (name: String!) is a required constructor parameter in a type, as name is above. A let field with no default is required too, while a let field with a default is not a parameter at all:

type Token {
  let value: String!
  let prefix = "tok_"
  masked: String! { prefix + "***" }
}

Token("abc123").masked
=> "tok_***"

A field's default runs once, while the object is being built, so it sees only values: the other fields and the enclosing scope, not self or methods (see Defaults see only values). Inside a type, its own let fields win over outer bindings of the same name:

let label = "outer"

type Tag {
  let label = "inner"
  show: String! { label }
}

Tag.show
=> "inner"

Visibility#

A field is public when it declares a type, and local when it starts with let. ada.greet and ada.bonus above are public; secret is local.

let introduces a local field. A type-level or top-level let is private to the module: any .dang file in the same directory can read it, but code that imports the module can't (see Modules and imports). That's how you share helpers across a module without exporting them. A block-level let is a fresh local.

Declaration vs. reassignment#

A bare name = value reassigns an existing field — see Mutation and copy-on-write. To declare a new field instead, give it a type or introduce it with let:

let total = 0   # declares a local field
total = 5       # reassigns it
total += 1      # compound update

total
=> 6

The new value must fit the field's declared type:

total = "six"
Type error: Reassignment.Infer: cannot assign String! to Int!: cannot use String! as Int!

Assigning a bare function name to a function-valued field calls the function. Use &name to assign the function itself (see Function references below):

type Clock {
  now: String! { "noon" }
}

later: String! { "midnight" }
let clock = Clock
clock.now = later
Type error: assigning `later` calls it and produces String!; use `&later` to assign the function itself ((): String!)
let clock = Clock
clock.now = &later
clock.now
=> "midnight"

Docstrings#

A """...""" literal right before a declaration documents it. A docstring is always verbatim, with no escapes or interpolation. This works on modules, types, fields, functions, function parameters, directives, and directive arguments:

"""
Greets the named user.
"""
welcome(
  """name of the person to greet"""
  name: String!
): String! {
  `welcome, ${name}!`
}

welcome("Ada")
=> "welcome, Ada!"

Functions#

A function is a field with an argument list. The last expression of the body is the result, so the normal result needs no return:

add(a: Int!, b: Int!): Int! { a + b }

add(2, 3)
=> 5

return expr is for leaving early. It unwinds through enclosing blocks and loops, and also works in new(...) constructors. Outside a function, method, or constructor it's an error (see Control flow). Forms in a body are separated by newlines or ;.

Zero-arity and auto-calling#

A function with no arguments drops the parentheses, both where it's declared and where it's called. It runs when referenced, like a property:

motd: String! { "hello" }

motd
=> "hello"

&motd gets the function without calling it (see below). GraphQL fields with no required arguments work the same way. With the bundled Demo schema (see GraphQL interop):

import Demo

serverInfo.version
→ query Query {serverInfo{version}}
=> "1.0.0"

Arguments#

Arguments can be named, positional, or both:

[add(a: 10, b: 20), add(10, 20), add(10, b: 20)]
=> [30, 30, 30]

Positional arguments come first, then named ones. The same rule applies to directive applications:

add(a: 10, 20)
Type error: positional arguments must come before named arguments

Defaults:

span(start: Int! = 0, end: Int! = start + 10): [Int!]! { [start, end] }

[span, span(5), span(5, 6)]
=> [[0, 10], [5, 15], [5, 6]]

A non-null parameter with a default (name: String! = "world") is nullable on the caller's side but non-null on the receiver's side. Callers may omit it, pass null, or pass a nullable String; each falls back to the default. Inside the body the parameter is a plain String!, so it needs no null checks. Prefer this over a nullable parameter whenever a sensible default (even a sentinel like "") exists: the caller can leave it out, and the body never sees null.

salute(name: String! = "world"): String! { "hi " + name }

let nobody = null :: String

[salute, salute(null), salute(nobody), salute("Ada")]
=> ["hi world", "hi world", "hi world", "hi Ada"]

Function references: &fn#

& (see Operators) gives you a function without calling it. You need it to store a function in a function-typed field, or to pass one as an argument. Here Greeter.hello is swapped for another function:

type Greeter {
  hello(name: String!): String! { `hello, ${name}` }
  greet(name: String!): String! { hello(name) }
}

shout(name: String!): String! { `HEY ${name.toUpper}` }

let loud = Greeter
loud.hello = &shout
loud.greet("ada")
=> "HEY ADA"

A function stored where another function type is expected must accept every argument that type promises (parameters are contravariant, results covariant), and name its parameters the same, in the same order: callers name arguments by the target's signature. wave takes who, not name:

wave(who: String!): String! { `*waves at ${who}*` }
let polite = Greeter
polite.hello = &wave
Type error: Reassignment.Infer: cannot assign (who: String!): String! to (name: String!): String!: cannot use (who: String!): String! as (name: String!): String!

Blocks are the exception: a block takes on the parameter names of the signature it's passed for.

Nested functions#

Functions declared inside a function, method, or new() body are closures, like blocks. They see the enclosing scope lexically, so its arguments and locals shadow fields inside them just as in the body. Their writes land in the enclosing scope, so bump here counts up across calls:

tally: [Int!]! {
  let n = 0
  bump: Int! { n += 1; n }
  let first = bump
  let second = bump
  [first, second, n]
}

tally
=> [1, 2, 2]

Meta: link forward to Blocks — block arguments are the more common form of "pass code." Function refs are for the cases where you need a true callable to store or rebind.

Forward references#

tl;dr: they work.

.dang files within a directory share a common scope, like in Go. A field may use fields declared later in the same file or in sibling files, and types may use types declared later:

area: Int! { width * height }
width: Int! = 3
height: Int! = 4

area
=> 12

A direct initializer cycle is rejected before the script runs:

first: Int! = second
second: Int! = first
Type error: variables phase failed: circular module variable initializer: first -> second -> first

A cycle hidden behind an auto-called function or a constructor default is caught at runtime, when the variable is first read. Run as a script, this reports initialization cycle while evaluating variable "start":

start: Int! = next
next: Int! { start + 1 }