Add entries to a Dict using DictEntry -- there is no curly-brace literal syntax.

← Collections and Data Structures · Ref: Q1179

EK9 has NO dict literal syntax. Build dicts with DictEntry:

  settings <- Dict() of (String, String)
  settings += DictEntry("theme", "dark")
  settings += DictEntry("lang", "en")

Do NOT try {"theme": "dark"} — it will not parse. Every entry uses DictEntry(key, value) added with +=.

See Q1178 for Dict creation. See Q1161 for full Dict operations.

Example

defines module qa.collections.dictnoliteralsyntax

  defines program

    DictNoLiteralSyntaxDemo()
      stdout <- Stdout()

      //WRONG: EK9 has no curly-brace dict literals
      //settings <- {"theme": "dark", "lang": "en"}  <- PARSE ERROR

      //RIGHT: Create Dict and add entries with DictEntry
      settings <- Dict() of (String, String)
      settings += DictEntry("theme", "dark")
      settings += DictEntry("lang", "en")
      settings += DictEntry("fontSize", "14")

      //Retrieve values
      theme <- settings.getOrDefault("theme", "light")
      stdout.println(`Theme: ${theme}`)

      lang <- settings.getOrDefault("lang", "en")
      stdout.println(`Language: ${lang}`)

      //Iterate
      for entry in settings
        stdout.println($entry)

Common mistakes

E50050 — EK9 has no curly-brace dict literal. Use Dict() of (K, V) and add entries with += DictEntry(k, v).

Incorrect:

      settings <- {"theme": "dark"}

Correct:

      settings += DictEntry("theme", "dark")
Other ways to ask this
  • Write code showing that EK9 dicts cannot use {key: value} literals
  • I keep getting errors trying to initialise a dict with curly braces in EK9
  • In JavaScript I'd use {name: 'Alice', age: 30}. What is the EK9 Dict equivalent?
  • Build a settings Dict the correct way using DictEntry instead of literal syntax

Coming from another language?

JavaScript: {key: value}. Python: {key: value}. Java: Map.of(k, v). Go: map[string]string{k: v}. EK9: NO literal syntax — use Dict() of (K, V) and += DictEntry(k, v).

Keywords: curly brace, no literal, syntax, Dict, DictEntry, literal