Define #^ on a record to promote it to String for display purposes.

← Operators and Expressions · Ref: Q1052

Define operator #^ on your record to return String. The compiler will use this automatically when a String is needed.

  defines record
    Colour
      red as Integer: 0
      green as Integer: 0
      blue as Integer: 0
      operator #^ as pure
        <- rtn as String: `rgb(${red}, ${green}, ${blue})`

Usage:

  crimson <- Colour(220, 20, 60)
  asString <- #^ crimson

Note: #^ and $ serve different purposes.
- $ is the string representation operator (called with $variable)
- #^ is the promotion operator (automatic type widening)

When a function expects a String parameter and you pass a Colour, the compiler calls #^ automatically. With $, you must explicitly write $colour.

Both are pure and take no parameters. The difference is intent: $ is for display, #^ is for type conversion.

See Q912 for what #^ means. See Q1048 for #^ on a class. See Q1055 for default vs manual operators.

Example

defines module qa.operators.promoterecordstring

  defines record

    Colour
      red as Integer: 0
      green as Integer: 0
      blue as Integer: 0

      Colour()
        ->
          red as Integer
          green as Integer
          blue as Integer
        this.red :=: red
        this.green :=: green
        this.blue :=: blue

      operator #^ as pure
        <- rtn as String: `rgb(${red}, ${green}, ${blue})`

      default operator

  defines program

    PromoteRecordDemo()
      stdout <- Stdout()

      crimson <- Colour(220, 20, 60)
      skyBlue <- Colour(135, 206, 235)

      //Explicit promote
      asString <- #^ crimson
      stdout.println(asString)

      //$ for display
      stdout.println(`Colour: ${skyBlue}`)

Common mistakes

E07420 — The #^ operator must return a different type. Returning the same record type triggers E07420.

Incorrect:

      operator #^ as pure
        <- rtn as Colour: Colour(red, green, blue)

Correct:

      operator #^ as pure
        <- rtn as String: `rgb(${red}, ${green}, ${blue})`
Other ways to ask this
  • How do I make a record automatically convert to String with #^?
  • Show a record with a promote operator that returns String
  • Use #^ to widen a record to its string representation

Coming from another language?

Java: toString() for display, casting for conversion. EK9 separates these: $ for display, #^ for type promotion.

Keywords: string, display, operator, promote, convert, record