E04020: result must be String, have the $ operator or can be promoted to String
What went wrong
A string interpolation expression contains a value that cannot be converted to String. The type needs either $ operator or #^ promotion.
Worked examples
Compilable examples demonstrating this error and the correct fix:
- ek9 -q 279 (Why does AI confuse EK9 operators with other languages?)
String conversion options
- The '$' operator - direct conversion. 'default operator $' generates one from the type's properties (good.ek9 in the [EXAMPLE] section below), or write your own.
- The '#^' operator returning a String - promotion. The value is promoted to a String wherever a String is wanted, an interpolation included (good_promotion.ek9 below).
[BUILT-IN TYPES] All built-in types work automatically:
- Integer, Float, Boolean (have $ operator)
- String (already a String)
- Date, Time, DateTime (have $ operator)
How to fix it
- Add a '$' operator to the type ('default operator $' or a written one)
- Or add a '#^' promotion that returns a String
- Or convert the value yourself first and interpolate the String you made
Common causes
- Custom class without string conversion operators
- Using 'Any' type in interpolation
- Third-party type without string support
Examples
Every example is compiled by the EK9 compiler: the first fails exactly as captioned, the others fix it.
Fails with E04020: result must be String, have the $ operator or can be promoted to String
#!ek9 defines module error.e04020.bad defines class //No '$' operator and no promotion to String Point x as Integer: 0 y as Integer: 0 default operator ? defines function describe() -> point as Point <- rtn as String: `The point is ${point}`
Fixed: Give the type a '$' operator (default operator $ generates one from its properties)
#!ek9 defines module error.e04020.good defines class Point x as Integer: 0 y as Integer: 0 default operator ? default operator $ defines function describe() -> point as Point <- rtn as String: `The point is ${point}`
Fixed: Or give the type a promotion to String ('#^')
#!ek9 defines module error.e04020.good.promotion defines class Point x as Integer: 0 y as Integer: 0 default operator ? //Promoted to a String wherever a String is wanted, an interpolation included operator #^ as pure <- rtn as String: `(${x}, ${y})` defines program ShowPoint() stdout <- Stdout() point <- Point() stdout.println(`The point is ${point}`)
Questions and answers
These Q&A entries show E04020 and its fix:
Found a problem?
If EK9 reported E04020 for a program you think is valid, or did not report it where it should have, use the compiler form with the smallest program that shows it. If this page is wrong or unclear, use the documentation form. Both are at github.com/ek9lang/ek9-issues.