How do I use the #? hashcode operator on a record?
← Operators and Expressions · Ref: Q1047
Records can use 'default operator' to auto-generate #? from all fields. The generated hashcode combines the hash values of every field.
defines record Coordinate latitude as Float: 0.0 longitude as Float: 0.0 default operator
Usage:
point <- Coordinate(51.5, -0.12) hash <- #? point
The default operator generates #? that combines #?latitude and #?longitude. You can also define it manually if you need custom logic:
operator #? as pure <- rtn as Integer: #?latitude + #?longitude
The #? operator always returns Integer. It must be pure. Records with default operator also get ==, $, :=:, and other operators automatically.
See Q911 for what #? means. See Q1053 for manual #? on a class. See Q1055 for default vs manual operators. See Q116 for what default operator generates.
Example
defines module qa.operators.hashcoderecord defines record Coordinate latitude as Float: 0.0 longitude as Float: 0.0 Coordinate() -> latitude as Float longitude as Float this.latitude :=: latitude this.longitude :=: longitude default operator defines program HashcodeRecordDemo() stdout <- Stdout() pointA <- Coordinate(51.5, -0.12) pointB <- Coordinate(51.5, -0.12) pointC <- Coordinate(48.8, 2.35) hashA <- #? pointA hashB <- #? pointB hashC <- #? pointC stdout.println(`A hash: ${hashA}`) stdout.println(`B hash: ${hashB}`) stdout.println(`C hash: ${hashC}`) stdout.println(`A == B: ${pointA == pointB}`) stdout.println(`A == C: ${pointA == pointC}`)
Other ways to ask this
- How does #? work on records in EK9?
- Show me hashcode with a record type
- Can records have a hashcode operator?
Coming from another language?
Java: records auto-generate hashCode(). Python: dataclasses can auto-generate __hash__(). EK9: 'default operator' on records generates #? from all fields.
Keywords: record, default, operator, integer, hashcode