Is the $ operator the same as string interpolation in EK9?

← Operators and Expressions · Ref: Q1056

No. The $ operator and string interpolation are completely separate things in EK9.

$ OPERATOR — converts any value to String:

  age <- 25
  ageAsString <- $age

This calls the _string() method on the value and returns a String. It works outside backtick strings as a standalone operator.

STRING INTERPOLATION — embeds values inside backtick strings:

  message <- `Age is ${age}`

This is backtick string syntax. The ${...} is interpolation that happens inside backtick strings only.

The confusion:

  $age outside backticks = calls _string() operator, returns String
  ${age} inside backticks = interpolation, embeds value in string

You can combine them:

  ${$myObject} inside backticks = explicitly calls _string() then interpolates

But usually ${myObject} is enough because interpolation calls _string() automatically.

Defining $ on a custom type:

  operator $ as pure
    <- rtn as String: `value: ${amount}`

The $ operator must be pure, take no parameters, and return String.

See Q908 for $ operator details. See Q43 for backtick string escaping. See Q1055 for default vs manual operators.

Example

defines module qa.operators.dollarnotinterpolation

  defines class

    Temperature
      celsius as Float: 0.0

      Temperature() as pure
        -> celsius as Float
        this.celsius :=: celsius

      //$ operator — converts to String
      operator $ as pure
        <- rtn as String: `${celsius}C`

      override operator ? as pure
        <- rtn as Boolean: celsius?

  defines program

    DollarDemo()
      stdout <- Stdout()

      reading <- Temperature(22.5)

      //$ operator: converts to String
      readingString <- $reading
      stdout.println(readingString)

      //Interpolation: embeds in backtick string
      stdout.println(`The temperature is ${reading}`)

      //Both together: explicit $ inside interpolation
      stdout.println(`Explicit: ${$reading}`)

Common mistakes

E50060 — EK9 has no .toString() method; `reading.toString()` triggers E50060 (method not resolved) - use the $ prefix operator: $reading calls _string(). See ek9 -h E50060 for details.

Incorrect:

      readingString <- reading.toString()

Correct:

      readingString <- $reading
Other ways to ask this
  • What is the difference between $variable and ${variable} in EK9?
  • Does $ mean interpolation in EK9?
  • How do I convert a value to String in EK9?

Coming from another language?

Java: toString(). Python: str() / __str__. JavaScript: template literals use ${} for interpolation. EK9 separates these: $ is the conversion operator, ${} is backtick interpolation.

Keywords: string, dollar, conversion, operator, backtick, interpolation