Convert a Customer record to both display string and JSON format.
← Operators and Expressions · Ref: Q1094
String and interpolation:
str <- $cust stdout.println(`Customer: ${cust}`)
Default operator $ generates ClassName(field=value) format. Works directly in backtick interpolation. See Q908 for $ string operator, Q887 for $$ JSON operator.
Example
defines module qa.operators.recordtostringjson defines class Customer name <- String() email <- String() age <- Integer() Customer() -> name as String email as String age as Integer this.name :=: name this.email :=: email this.age :=: age default operator defines program RecordToStringJsonDemo() stdout <- Stdout() cust <- Customer("Alice", "alice@example.com", 30) //$ string representation str <- $cust stdout.println(`String: ${str}`) //In backtick interpolation stdout.println(`Customer: ${cust}`)
Common mistakes
E50060 — EK9 has no Java-style '.toString()' method; use the '$' prefix operator for string conversion. See ek9 -h E50060 for details.
Incorrect:
str <- cust.toString()
Correct:
str <- $cust
Other ways to ask this
- I need to print a record as a readable string and also serialise it to JSON
- In Java I'd override toString() and write a toJson(). Write the EK9 equivalent
- Given a class with name and email, produce $ string and $$ JSON representations
- Generate both human-readable and JSON output from a single record
Coming from another language?
Java: toString() and manual JSON. Python: __str__ and json.dumps(). Rust: Display + serde. EK9: default operator $ and default operator $$ — one line each.
Keywords: string, $$, convert, serialise, $, JSON, display