Enums and scalars#

Meta: split this 50/50 — both feel obvious on the page but trip people up in real code (enum literal vs. string, scalar coercion timing).

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.

Enums#

Declaration#

An enum lists its members as bare CAPS names:

enum Color { RED GREEN BLUE }

Members are separated by spaces or newlines, not commas:

enum Size { SMALL, LARGE }
Parse error: syntax error: unexpected ', LARGE'

Values#

A value is written with its enum's name, as Color.RED. An enum value is a field on the enum (see Modules and imports), not a top-level name, so a bare RED isn't in scope, even inside case. (Enums imported from a schema are the exception, below.)

RED
Type error: "RED" not found

Color.values lists every member, as a real [Color!]!:

Color.values
=> [Color.RED, Color.GREEN, Color.BLUE]

Two values of the same enum are equal when they're the same member. Values of different enums can't be compared, even when the member names match:

enum Signal { RED AMBER GREEN }

Color.RED == Color.RED
=> true
Color.RED == Signal.RED
Type error: cannot compare Color! with Signal!: they are unrelated types

A string literal compared with an enum value converts to it, as it does in an argument, so it must name a member. Color.RED is still the clearer spelling:

let shade = Color.BLUE

[shade == "BLUE", shade != "RED"]
=> [true, true]

A String held in a variable doesn't convert; cast it with :: (below):

let picked = "BLUE"
shade == picked
Type error: cannot compare Color! with String!: they are unrelated types; compare with a Color value, like Color.RED, or cast the string: (picked :: Color!)

As function arguments#

An enum is an ordinary parameter type. A string literal naming a member works too, and is checked before the script runs:

paint(c: Color!): String! { `painted ${c}` }

[paint(Color.GREEN), paint("BLUE")]
=> ["painted GREEN", "painted BLUE"]
paint("PURPLE")
Type error: argument "c": "PURPLE" is not a value of Color; expected one of RED, GREEN, BLUE

Enums from a schema work the same way, including inside input objects. With the bundled Demo schema (see GraphQL interop):

import Demo

usersByStatus(status: Status.ACTIVE).{{ name }}.map { _.name }
→ query Query {usersByStatus(status:ACTIVE){name}}
=> ["John Doe"]

An imported enum's values are also in scope bare, as long as no other import uses the same name (see Modules and imports):

usersByStatus(status: PENDING).{{ name }}.map { _.name }
→ query Query {usersByStatus(status:PENDING){name}}
=> ["Jane Smith"]
let byNameDesc = UserSort(field: UserSortField.NAME, direction: SortDirection.DESC)

sortedUsers(sort: byNameDesc).{{ name }}.map { _.name }
→ query Query {sortedUsers(sort:{direction:DESC,field:NAME}){name}}
=> ["Jane Smith", "John Doe"]

In case#

Value patterns are the qualified members (or string literals). A case that names every member is exhaustive: it needs no else, and its result stays non-null:

action(c: Color!): String! {
  case (c) {
    Color.RED => "stop"
    Color.GREEN => "go"
    Color.BLUE => "wait"
  }
}

[action(Color.RED), action(Color.BLUE)]
=> ["stop", "wait"]

Leave a member out and the case can fall through to null, so it no longer fits a String!. Add the member, or an else:

caution(c: Color!): String! {
  case (c) {
    Color.RED => "stop"
    Color.GREEN => "go"
  }
}
Type error: return type mismatch: declared String!, inferred String

A nullable operand also needs a null => arm (see Control flow).

From strings (::)#

A string that isn't a literal becomes an enum value with a :: cast. The cast checks the string when it runs:

let favorite = "GREEN"

favorite :: Color!
=> Color.GREEN
let wanted = "PURPLE"
wanted :: Color!
Runtime error: invalid enum value "PURPLE" for Color

Custom scalars#

Declaration#

scalar Email
scalar Semver

A custom scalar is a string with its own type. An Email! and a String! are different types.

Coercion#

A literal converts to a compatible scalar wherever a value is handed over: call arguments, typed slots, list and map literals, and return values. That covers string literals, list and map literals, and templates, even ones with ${...} inside:

sendTo(to: Email!): String! { `mail for ${to}` }

let name = "grace"

[sendTo("ada@example.com"), sendTo(`${name}@example.com`)]
=> ["mail for ada@example.com", "mail for grace@example.com"]

A string that isn't a literal, such as a variable or a + b, doesn't convert:

let address = "ada@example.com"
sendTo(address)
Type error: argument "to": cannot use String! as Email!

It needs an explicit :: cast:

sendTo(address :: Email!)
=> "mail for ada@example.com"

List literals don't convert their elements to match each other, so a plain string doesn't join a list of Email!s:

["ada@example.com" :: Email!, "grace@example.com"]
Type error: unify index 1: no common type between String! and Email!

Only a String, or a value of another custom scalar (see below), converts to a scalar. 42 :: Email! is a type error:

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

Scalars from GraphQL responses need no cast. Demo's homepage is a URL!, and fetchURL takes one:

fetchURL(url: homepage)
→ query Query {homepage} → query Query {fetchURL(url:"https://danglang.org")}
=> "Fetched: https://danglang.org"

Some APIs define custom scalars (like a JSON scalar) whose values are numbers, booleans, or even structured JSON. Dang keeps those values as they are: passed back as an argument, one is sent unchanged, and where a String is expected (degrading, interpolation, toString) it reads as its JSON text. Demo's Opaque scalar is one of these:

[describeOpaque(value: opaqueNumber), `object: ${opaqueObject}`]
→ query Query {opaqueNumber} → query Query {describeOpaque(value:42)} → query Query {opaqueObject}
=> ["42", "object: {\"name\":\"dang\",\"size\":1.5,\"tags\":[\"a\",\"b\"]}"]

A schema's scalar JSON is a schema scalar like the ones above, its values as the server sends them. Unqualified, JSON is Dang's own scalar of JSON text (see JSON, YAML, and TOML), a separate type, and decoded data of any shape is Decoded (see Keeping data undecoded). Distinct scalars never mix on their own, but a cast converts one to another, validating at the target, so j :: Dagger.JSON! and d :: JSON! both work:

let pair = ("[1, 2]" :: JSON!)
let pairEmail = (pair :: Email!)

[(pairEmail :: JSON!) == pair, (pairEmail :: String!) == "[1, 2]"]
=> [true, true]

Text the target rejects fails the cast:

("ada@example.com" :: Email!) :: JSON!
Runtime error: invalid JSON: invalid character 'a' looking for beginning of value

Treating scalars as opaque#

Scalars support equality and list membership, and can go in records and lists. They are Ordered (see Type parameters, Ordered and Numeric): < and .sort compare them by their string form, numerically for a scalar whose value is a number. They have no string methods:

let ada: Email! = "ada@example.com"
let bob: Email! = "bob@example.com"

[ada == ada, [ada].contains(ada), ada < bob]
=> [true, true, true]
ada.toUpper
Type error: field "toUpper" not found in Email

Meta: the :: rule is the durable contract — literals are a convenience, non-literal values always go through an explicit cast.

Degrading to String#

A scalar value turns back into a String! wherever a value is handed over: typed slots, call arguments, return values, reassignment, ::, and case-clause values. It's a string underneath:

let plain: String! = ada

shout(msg: String!): String! { msg.toUpper }

[plain, shout(ada), `to: ${ada}`]
=> ["ada@example.com", "ADA@EXAMPLE.COM", "to: ada@example.com"]

A string literal compared with a scalar converts to it, like a literal argument. A String held in a variable doesn't; cast it first:

[ada == "ada@example.com", ada == (plain :: Email!)]
=> [true, true]
ada == plain
Type error: cannot compare Email! with String!: they are unrelated types; cast the string to compare: (plain :: Email!)

A String method needs a String receiver, so degrade first:

(ada :: String!).toUpper
=> "ADA@EXAMPLE.COM"

Scalar bodies#

A scalar can have a body. Its new() hook takes the raw string and returns the canonical one. It runs every time a value is made: a string literal in a Slug! slot, a :: Slug! cast, a codec decode, and the Slug(...) constructor that declaring new() adds:

scalar Slug {
  new(raw: String!) {
    raw.trimSpace.toLower.replace(" ", "-")
  }

  words: [String!]! { (self :: String!).split("-") }
  first: String! { words[0] ?? "" }
}

Slug("  Hello World  ")
=> "hello-world"

Since every value goes through new(), equality compares the normalized strings:

Slug("A b") == Slug("a-b")
=> true

Members must be methods: a scalar holds nothing but its string. Inside a method, self is the scalar value, and sibling methods can be called bare:

Slug("one two three").first
=> "one"
scalar Version { major: Int! = 1 }
Type error: scalar member "major" must be a method; scalars carry no fields beyond their underlying string

A raise in the hook rejects a bad value, and rescue can recover from it at the spot where the value was made:

scalar Upper {
  new(raw: String!) {
    if (raw != raw.toUpper) { raise `not upper: ${raw}` }
    raw
  }

  self {
    of(s: String!): Upper! { Upper(s.toUpper) }
  }
}

Upper("nope") rescue { e: Error! => e.message }
=> "not upper: nope"

A scalar's self { } block declares statics exactly like a type's (see Static members):

Upper.of("mixed Case")
=> "MIXED CASE"

Built-in scalars#

ID! is its own scalar, not a String alias. String literals still convert into ID! slots, but a String! value doesn't:

let key: ID! = "abc"
let text = "abc"
let other: ID! = text
Type error: cannot use String! as ID!

Path normalizes as it's made:

"src/../docs/./index.md" :: Path!
=> "docs/index.md"

Meta: scalar fields are invariant across interface implementation — id: String! does not satisfy id: ID!. Cross-ref the variance rules in Interfaces and unions.

See also: enum values and custom scalars declared in an imported schema are reachable through the module name (Demo.Status.ACTIVE), unqualified (Status.ACTIVE), or, for enum values, bare when no other import uses the name (see Modules and imports); GraphQL representations are covered in GraphQL interop.