Objects (type)#

Meta: lead with "a type declares both a type and its prototype constructor." That's the unusual thing. Cross-link to Mutation and copy-on-write — don't try to explain CoW here.

A type declaration makes two things: a type, and a constructor function of the same name.

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.

Declaration#

type Person {
  name: String!
  age: Int! = 0

  greet: String! {
    "hi, I'm " + name
  }
}

Person("Alice").greet
=> "hi, I'm Alice"

Public vs. private members#

let privacy is module-scoped, not type-scoped, so another type in the same module can read a let member:

type Account { let secret: String! = "hunter2" }
type Vault { unlock(a: Account!): String! { a.secret } }

Vault.unlock(Account)
=> "hunter2"

Whether a member is a constructor parameter depends on whether it has a default, not on its visibility:

Implicit constructor#

Without a new, the constructor takes the parameters listed above, in declaration order. It can be called with positional arguments, named ones, or both:

[Person("Alice", age: 30).age, Person(name: "Bob").age, Person("Cy", 41).age]
=> [30, 0, 41]

Declaration order means a defaulted field can come before a required one, and positional arguments still line up with the declarations. Here the first positional argument goes to label:

type Ticket {
  label: String! = "general"
  let seat: Int!
  show: String! { `${label} #${seat}` }
}

Ticket("vip", 12).show
=> "vip #12"
Ticket(12)
Type error: argument "label": cannot use Int! as String

Name the argument to skip the defaulted field: Ticket(seat: 12).

Field defaults are the constructor's parameter defaults, so a default may use other fields. They run while the object is built, so they see only values, not self or methods (see Defaults see only values):

type Slot {
  prefix: String!
  suffix: String! = "end"
  combined: String! = prefix + "_" + suffix
}

Slot("start").combined
=> "start_end"

Zero-arg auto-construction#

Functions and constructors auto-call on bare reference when every parameter is nullable or has a default, and no block argument is required. Settings is therefore the same as Settings():

type Settings {
  verbose: Boolean! = false
  label: String
}

let settings = Settings
settings.verbose
=> false

A bare reference to a function that requires a block argument is an error, the same as calling it without a block. Use &name to reference it without calling it:

twice(&body: Int!): Int! { body + body }
let doubled = twice
Type error: function requires a block argument

Explicit constructor: new#

type Greeter {
  greeting: String!

  new(name: String!) {
    self.greeting = "hello, " + name
    self
  }
}

Greeter("Ada").greeting
=> "hello, Ada"

new takes no pub and no return type, and is only valid inside a type body:

type Gadget {
  size: Int! = 1
  new(): Gadget! { self }
}
Type error: 'new' is a constructor, not a method; use `new(...) { ... }` without `pub` or a return type

Constructor arguments are local bindings, separate from fields even when they share a name. Reassigning text here rebinds the argument; the field is written with self.text =. The arguments are visible only in new, not in methods:

type Shout {
  text: String!

  new(text: String!) {
    text = text.toUpper
    self.text = text + "!"
    self
  }
}

Shout("hey").text
=> "HEY!"

The body must return the constructed type (self, or a method chain that returns it). Returning another type, or null, is an error:

type Broken {
  size: Int! = 1
  new { "not a Broken" }
}
Type error: new() must return Broken!, got String!

A constructor can end with a method chain, and its field writes add up, even inside a loop:

type Counter {
  value: Int! = 0
  bump: Counter! { value += 1; self }

  new(times: Int!) {
    [1, 2, 3].each { i => if (i <= times) { value += 1 } }
    self.bump
  }
}

Counter(2).value
=> 3

self#

Computed fields#

A member with a type and a body but no argument list is a computed field. It reads like a plain field (obj.full, no parentheses) and runs again on every access, against the current receiver. A member with a default value, by contrast, is computed once, when the object is built:

type FullName {
  first: String!
  last: String!
  full: String! { first + " " + last }       # every access
  original: String! = first + " " + last     # once, at construction
}

let author = FullName("Ada", "Lovelace")
author.first = "Augusta"

[author.full, author.original]
=> ["Augusta Lovelace", "Ada Lovelace"]

Static members#

A self { } block declares statics. They live on the type itself, reached as Type.member, never on an instance:

type Color {
  r: Int! = 0
  g: Int! = 0
  b: Int! = 0

  luminance: Int! { (r + g + b) / 3 }        # an instance member

  self {
    white: Color! { Color(r: 255, g: 255, b: 255) }   # a factory method
    fromGray(v: Int!): Color! { Color(r: v, g: v, b: v) }
    grayMid: Color! { fromGray(128) }                 # a static calling a sibling static
    let scale = 2                                      # a private (let) static helper
    doubled(v: Int!): Int! { v * scale }
  }
}

[Color.white.luminance, Color.fromGray(10).r, Color.grayMid.g, Color.doubled(7)]
=> [255, 10, 128, 14]

Instances don't have the statics, and a bare all-default type still auto-constructs, so Color.luminance reads an instance member:

[Color(r: 3, g: 6, b: 9).luminance, Color.luminance]
=> [6, 0]
Color(r: 1).white
Type error: field "white" not found in Color

Static stored fields hold singleton values on the type:

type Config {
  host: String! = "localhost"

  self {
    limit: Int! = 100
    default: Config! = Config    # a static holding a constructed instance
  }
}

Config.limit
=> 100
Config.default.host
=> "localhost"

Statics are immutable, from everywhere (see Functions return, they don't write):

Config.limit = 5
Type error: cannot assign to `Config.limit`: static members are immutable once initialized; a static method's writes to `self` stay in that call's copy

A scalar may also carry a self { } block, including static stored fields, even though a scalar can't have instance stored fields (see Scalar bodies).

Implements#

interface Named { name: String! }
interface Identifiable { id: String! }

type Member implements Named & Identifiable {
  name: String!
  id: String!
}

describe(n: Named!): String! { `named ${n.name}` }

describe(Member("Ada", "m1"))
=> "named Ada"

Forward references#

type Order {
  total: Int! = price * quantity   # declared before the fields it uses
  price: Int! = 5
  quantity: Int! = 2
  receipt: Receipt! { Receipt(total) }
}

type Receipt { amount: Int! }

Order.receipt.amount
=> 10

Meta: user-defined types and imported GraphQL input types share the same Type(args) construction syntax. Schema input types are constructed exactly like local types: CreateUserInput(name: "Alice", email: "...") passed as Mutation.createUser(input: ...). See GraphQL interop.