Verify that two equal objects produce the same hashcode.

← Operators and Expressions · Ref: Q1096

Hashcode prefix operator:

  h1 <- #?p1
  h2 <- #?p2
  assert h1 == h2

Equal objects must have equal hashes. 'default operator' generates #? and == from the same fields, ensuring consistency. See Q966 for hashcode details, Q1095 for using records as Dict keys.

Example

defines module qa.operators.hashcodeoperator

  defines class

    Point
      x <- Integer()
      y <- Integer()

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

      default operator

  defines program

    HashcodeOperatorDemo()
      stdout <- Stdout()

      p1 <- Point(10, 20)
      p2 <- Point(10, 20)
      p3 <- Point(99, 20)

      //Equal objects must have equal hashcodes
      h1 <- #?p1
      h2 <- #?p2
      stdout.println(`p1 hash: ${h1}`)
      stdout.println(`p2 hash: ${h2}`)

      if h1 == h2
        stdout.println("Hash contract holds: equal objects, equal hashes")

      //Different objects likely have different hashes
      h3 <- #?p3
      stdout.println(`p3 hash: ${h3}`)

Common mistakes

E50060 — EK9 uses the '#?' prefix operator for hashcodes, not a '.hashCode()' method — 'p1.hashCode()' does not resolve. See ek9 -h E50060 for details.

Incorrect:

h1 <- p1.hashCode()

Correct:

h1 <- #?p1
Other ways to ask this
  • I need to confirm the hash contract holds for my custom class
  • In Java I'd test that hashCode() is consistent with equals(). Show the EK9 equivalent
  • Given two objects with identical field values, check their #? hashcodes match
  • Test hashcode consistency between equal objects using #?

Coming from another language?

Java: obj.hashCode(). Python: hash(obj). Rust: Hash trait. EK9: #?obj prefix operator — no method call needed.

Keywords: hashcode, consistency, #?, equal, hash, contract