How do I make my own class work with the $ operator in EK9?

← Operators and Expressions · Ref: Q995

The $ operator calls the _string() method. To customise it for your own class, either use 'default operator' (auto-generates from fields) or implement operator $ yourself.

USING DEFAULT OPERATOR:

  default operator

This auto-generates $ (and other operators) from your class fields.

CUSTOM IMPLEMENTATION:

  operator $ as pure
    <- rtn as String: `${accountHolder}: ${$currentBalance}`

The operator must be marked 'as pure', take no parameters, and return a String.

USAGE:

  account <- BankAccount("Alice", 1000.0)
  description <- $account       calls your _string() method
  stdout.println($account)      same — converts then prints

Example

defines module qa.operators.dollarcustomclass

  defines class

    TemperatureSensor
      location as String: String()
      currentReading as Float: 0.0

      TemperatureSensor()
        ->
          location as String
          currentReading as Float
        this.location: location
        this.currentReading: currentReading

      //Custom $ operator — controls what $sensor produces
      operator $ as pure
        <- rtn as String: `${location}: ${currentReading}C`

      default operator

  defines program

    DollarCustomDemo()
      stdout <- Stdout()

      sensor <- TemperatureSensor("Kitchen", 22.5)

      // $ calls our custom operator $
      sensorText <- $sensor
      stdout.println(sensorText)

      // Same thing inline
      stdout.println($sensor)

Common mistakes

E50060 — EK9 has no toString() method. Use $variable to convert to String: stdout.println($sensor). The $ calls the operator $ (which calls _string()) on the object.

Incorrect:

      stdout.println(sensor.toString())

Correct:

      stdout.println($sensor)
Other ways to ask this
  • How do I define a custom string conversion for my EK9 class?
  • What method does $ call on my class?
  • How do I control what $myObject produces in EK9?

Coming from another language?

EK9 uses 'operator $' to define string conversion. This replaces Java's toString(), Python's __str__(), Rust's Display trait.

Keywords: toString, string, dollar, custom, class, operator