How do I convert a value to a String in EK9?

← Operators and Expressions · Ref: Q994

Prefix any variable with $ to convert it to a String. The $ operator calls the _string() method on the object.

EXAMPLES:

  age <- 25
  ageText <- $age                converts Integer 25 to String "25"
  price <- 19.99
  priceText <- $price            converts Float 19.99 to String "19.99"
  active <- true
  activeText <- $active          converts Boolean to String "true"

INSIDE BACKTICK STRINGS:

Within backtick strings, ${expression} evaluates the expression and converts to String automatically:

  stdout.println(`Age: ${$age}`)   explicit $ conversion inside ${}
  stdout.println(`Age: ${age}`)    implicit conversion — same result for String types

The $ prefix and ${} backtick syntax are different things:

  $variable      standalone conversion — returns a String value
  ${expression}  backtick syntax — embeds expression result in a string

Example

defines module qa.operators.dollarconverts

  defines program

    DollarConvertsDemo()
      stdout <- Stdout()

      // $ converts Integer to String
      age <- 25
      ageText <- $age
      stdout.println(`Age as String: ${ageText}`)

      // $ converts Float to String
      price <- 19.99
      priceText <- $price
      stdout.println(`Price as String: ${priceText}`)

      // $ converts Boolean to String
      isActive <- true
      activeText <- $isActive
      stdout.println(`Active as String: ${activeText}`)

      // $ on a String is identity — returns the same String
      greeting <- "Hello"
      sameGreeting <- $greeting
      stdout.println(sameGreeting)

      // Use $ when you need an explicit String for concatenation or assignment
      itemCount <- 42
      summary <- "Items: " + $itemCount
      stdout.println(summary)

Common mistakes

E50060 — EK9 has no toString() method. Use the $ prefix operator: $variable converts any value to String by calling _string().

Incorrect:

      ageText <- age.toString()

Correct:

      ageText <- $age
Other ways to ask this
  • What does the $ prefix do to a variable in EK9?
  • How do I get the string representation of an Integer or Float?
  • Show me how to convert numbers to strings in EK9

Coming from another language?

EK9 uses $variable as a prefix conversion operator. It calls _string() and returns a String.

Keywords: convert, dollar, prefix, string, toString