Use a Coordinate record as a Dict key.

← Operators and Expressions · Ref: Q1095

Using a record as a Dict key:

  grid <- Dict() of (Coordinate, String)
  grid += DictEntry(Coordinate(0, 0), "origin")

Dict keys need #? (hashcode) and == (equality). Use 'default operator' to generate both from declared fields, ensuring the hash contract holds automatically. See Q966 for hashcode details, Q1083 for equality.

Example

defines module qa.operators.recordasdictkey

  defines class

    Coordinate
      x <- Integer()
      y <- Integer()

      Coordinate()
        ->
          x as Integer
          y as Integer
        this.x :=: x
        this.y :=: y

      default operator

  defines program

    RecordAsDictKeyDemo()
      stdout <- Stdout()

      //Use Coordinate as Dict key — needs (K, V) parentheses
      grid <- Dict() of (Coordinate, String)
      grid += DictEntry(Coordinate(0, 0), "origin")
      grid += DictEntry(Coordinate(1, 0), "east")
      grid += DictEntry(Coordinate(0, 1), "north")

      stdout.println(`Grid entries: ${grid.length()}`)

      //Look up by equal key using getOrDefault
      lookup <- Coordinate(1, 0)
      result <- grid.getOrDefault(lookup, "unknown")
      stdout.println(`Found: ${result}`)

Common mistakes

E07235 — EK9 has no hashCode() method. Use 'default operator #?' or 'default operator' to generate hashcode from fields.

Incorrect:

      hashCode()
        <- rtn as Integer: x * 31 + y

Correct:

      default operator
Other ways to ask this
  • I need to store values in a Dict keyed by a custom class — what operators are required?
  • In Java I'd implement hashCode() and equals(). Write the EK9 equivalent for Dict keys
  • Given a Coordinate class, set up the operators needed to use it as a Dict key
  • Make a custom type usable as a dictionary key with #? and == operators

Coming from another language?

Java: implement hashCode() and equals(). Python: __hash__ and __eq__. Rust: Hash + PartialEq. EK9: default operator generates #? and == from fields.

Keywords: ==, equality, Dict, key, #?, map, hashcode