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

- Every field needs a default value: 'xPos <- 0.0' not 'xPos as Float'
- Add 'operator <=>' (comparator) then 'default operator' to auto-generate ==, <>, $, #?
- 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
        -> arg0 as Coordinate
        <- rtn as Integer: xPos <=> arg0.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: operator, default, data, field, record, public, struct