What does the #? hashcode operator do in EK9?

← Operators and Expressions · Ref: Q966

The #? operator is the HASHCODE operator in EK9. It calls the _hashcode() method on the object and returns an Integer.

Syntax: #? variableName (prefix operator)

IMPORTANT: #? is NOT a Python comment. It is NOT a Ruby method call. The # prefix in EK9 means 'introspection' — #? is hashcode, #^ is promote, #< is first, #> is last.

EK9 operator method names:

  #? calls _hashcode() — returns Integer
  #^ calls _promote() — returns a different type (type widening)
  $ calls _string() — returns String (string CONVERSION)
  ? calls _isSet() — returns Boolean

The 'default operator' keyword auto-generates #? from declared fields. You rarely need to implement it manually.

Bridge: Like Java's hashCode() but as a prefix operator. Like Python's hash() but with # prefix syntax.

Example

defines module qa.operators.hashcodedetail

  defines record

    <?-
      Simple record with auto-generated #? operator via 'default operator'.
    -?>
    Coordinate
      latitude as Float: Float()
      longitude as Float: Float()

      Coordinate()
        ->
          latitude as Float
          longitude as Float
        this.latitude :=: latitude
        this.longitude :=: longitude

      default operator

  defines program

    HashcodeDemo()
      stdout <- Stdout()

      // #? on built-in types
      greeting <- "Hello"
      nameHash <- #? greeting
      stdout.println(`String hash: ${nameHash}`)

      age <- 42
      ageHash <- #? age
      stdout.println(`Integer hash: ${ageHash}`)

      // #? on custom record (auto-generated by 'default operator')
      location <- Coordinate(51.5074, -0.1278)
      locationHash <- #? location
      stdout.println(`Coordinate hash: ${locationHash}`)

      // Comparing hashcodes
      sameLocation <- Coordinate(51.5074, -0.1278)
      if #? location == #? sameLocation
        stdout.println("Same hashcodes for equal coordinates")

Common mistakes

E50060 — EK9 has no Java-style '.hashCode()' method; use the '#?' prefix operator, as 'hashCode' resolves on no EK9 type. See ek9 -h E50060 for details.

Incorrect:

      nameHash <- greeting.hashCode()

Correct:

      nameHash <- #? greeting
Other ways to ask this
  • How do I get a hashcode in EK9?
  • What is #? in EK9?
  • How does hashcode work in EK9?
  • What does hash question mark mean in EK9?

Coming from another language?

Java: obj.hashCode() — EK9: #? obj. Python: hash(obj) — EK9: #? obj. Kotlin: obj.hashCode() — EK9: #? obj. The # prefix is EK9's introspection family, NOT a comment character.

Keywords: introspection, prefix operator, hash, hashcode