How do I define a record with fields in EK9?
← Classes and OOP · Ref: Q876
If you are coming from Java, think Java record. From Rust, think struct. From Kotlin, think data class.
EK9 records are pure data containers. Their fields are PUBLIC (unlike class fields which are always private). They cannot have regular methods — only constructors and operators.
IMPORTANT RULES
- Simplest: give every field an initial value: 'xPos <- 0.0' not 'xPos as Float' (E08180). Alternatively declare it unset ('xPos as Float?'), provide a coded constructor that sets it AND make the no-arg constructor private ('default private Coordinate()'); without the constructor the compiler raises E07170, and with it but a public default constructor E07175
- Add 'operator <=>' (comparator) with a matching 'operator #?' hashing the same fields; ==, <>, <, >, <=, >= are generated from '<=>', and 'default operator' auto-generates $ and ?
- Use ':=:' in constructors to copy parameter values to fields
See Q97 for class vs record differences. See Q98 for record operators. Use 'ek9 -h record' for full syntax.
Example
defines module qa.classes.record.basics defines record Coordinate xPos <- 0.0 yPos <- 0.0 Coordinate() -> initialX as Float initialY as Float xPos :=: initialX yPos :=: initialY operator <=> as pure -> other as Coordinate <- rtn as Integer: xPos <=> other.xPos operator #? as pure <- rtn as Integer: #?xPos default operator defines program RecordDemo() stdout <- Stdout() origin <- Coordinate(0.0, 0.0) point <- Coordinate(3.0, 4.0) if point? stdout.println("Point: " + $point) stdout.println(`Equal: ${origin == point}`)
Other ways to ask this
- What is the syntax for EK9 records?
- How are records different from classes in EK9?
- Show me a simple EK9 record
Coming from another language?
Java: record keyword (Java 16+). Kotlin: data class. Python: dataclass. Rust: struct. EK9: defines record with public fields and auto-generated operators.
Keywords: data, default, operator, struct, public, record, field