Create me a Product record and use the SINGLE-dollar $ operator to convert it to a plain-text human-readable String.

← Operators and Expressions · Ref: Q1255

The SINGLE-dollar operator $ produces a PLAIN-TEXT String representation of a value. It is the EK9 equivalent of Java's toString() or Python's __str__. Override 'operator $' on a user-defined record to control what $ returns.

PRODUCT RECORD WITH $ OVERRIDE

  Product
    sku as String: String()
    name as String: String()
    price as Float: 0.0
    Product()
      ->
        sku as String
        name as String
        price as Float
      this.sku :=: sku
      this.name :=: name
      this.price :=: price
    override operator $ as pure
      <- rtn as String: `${sku} ${name} £${price}`
    default operator ?

USAGE

  product <- Product("SKU-42", "Widget", 9.99)
  plainText <- $product
  stdout.println(plainText)
  // Output: SKU-42 Widget £9.99

WHAT $ DOES

- Returns a String that is human-readable
- Uses backtick string interpolation for flexible formatting
- Is the OPPOSITE of $$ — $ is plain text, $$ is JSON (see Q1256)

This file uses ONLY the $ operator so the distinction from $$ is absolutely clear. Every use of the dollar sign here is single-dollar.

See Q1256 for the $$ JSON operator contrast. See Q1094 for $ and $$ in context. See Q887 for the JSON operator return type.

Example

defines module qa.operators.dollarstringproduct

  defines record

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

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

      operator $ as pure
        <- rtn as String: `${sku} ${name} £${price}`

      default operator ?

  defines program

    DollarStringProductDemo()
      stdout <- Stdout()

      product <- Product("SKU-42", "Widget", 9.99)
      plainText <- $product
      stdout.println(plainText)

Common mistakes

E07580 — '$' and '$$' are different operators: '$$' is the JSON operator and must return a JSON, while '$' returns plain text. See ek9 -h E07580 for details.

Incorrect:

operator $$ as pure

Correct:

operator $ as pure
Other ways to ask this
  • Show me how to use the $ operator on a custom record for human-readable output.
  • Write a Product record with a $ operator that returns a plain String.
  • Give me a record example that uses just the $ operator, not $$.
  • How do I override operator $ to produce a String representation of a record?

Coming from another language?

Java: toString() override. Kotlin: override fun toString(). Python: __str__. Rust: impl Display. Scala: override def toString. C#: override ToString(). EK9: 'operator $' produces a plain-text String. 'operator $$' produces JSON — the two are DIFFERENT.

Keywords: Product, dollar, plain text, toString, human readable, $, string operator