Define a Product record with name, price, and a constructor.

← Classes and OOP · Ref: Q1175

Define a record with public fields, a constructor, and default operator:

  defines record
    Product
      name as String: String()
      price as Float: 0.0
      Product()
        -> ...
      default operator

Record fields are always public (accessed directly with product.name). Records cannot have methods — only constructors and operators. Use 'default operator' to auto-generate standard operators. See Q97 for class vs record. See Q1060 for record field visibility.

Example

defines module qa.classesandoop.definerecord

  defines record

    Product
      name as String: String()
      price as Float: 0.0

      Product()
        ->
          name as String
          price as Float
        this.name: name
        this.price: price

      default operator

  defines program

    DefineRecordDemo()
      stdout <- Stdout()

      // Create a product using the constructor
      widget <- Product("Widget", 19.99)

      // Access fields directly (public)
      stdout.println(`Name: ${widget.name}`)
      stdout.println(`Price: ${widget.price}`)

      // Default operators provide $, ==, <>, <=> etc.
      stdout.println(`Product: ${widget}`)

      // Create another and compare
      gadget <- Product("Gadget", 29.99)
      stdout.println(`Equal: ${widget == gadget}`)

      // Records in a list
      products <- [widget, gadget, Product("Gizmo", 9.99)]
      for product in products
        stdout.println(`${product.name}: \$${product.price}`)

Common mistakes

E07290 — Records can only have constructors and operators, not methods. Adding a method like getName() triggers E07290. Access record fields directly since they are public. See ek9 -h E07290 for details.

Incorrect:

getName()
        <- rtn as String: name

Correct:

default operator

E50060 — Record fields are public and accessed directly without parentheses. Using product.name() tries to call a method, but records do not have accessor methods. See ek9 -h E06180 for details.

Incorrect:

product.name()

Correct:

product.name
Other ways to ask this
  • Write code to create a simple data record in EK9
  • I need a lightweight data type with public fields for name and price
  • Given name and price fields, define a record type with default operators
  • In Java I'd use record Product(String name, double price). Write the EK9 equivalent

Coming from another language?

Java: record Product(String name, double price) — immutable, auto accessors. Python: @dataclass class Product. Rust: struct Product { name: String, price: f64 }. Kotlin: data class Product(val name: String, val price: Double). EK9: defines record with public fields, mutable by default, 'as pure' controls mutability.

Keywords: default operator, record, product, fields, constructor, define, data, public