in an already instantiated string instance? For example, the string template contains the
$variable
pattern is parsed from an external file, and I want to auto interpolate the variables.
k
Klitos Kyriacou
02/02/2024, 11:04 AM
No. Interpolation is done at compile time.
j
Joffrey
02/02/2024, 12:36 PM
I mean, you can always replace a pattern in a string, if that's your question. It will not be related to any of your variable names of course, but you can still do it. For instance:
Copy code
val rawTemplate = "Hello \$name" // $ is escaped, so it's part of the actual string
println(rawTemplate) // "Hello $name"
val myName = "Joffrey"
val s = rawTemplate.replace("\$name", myName)
println(s) // "Hello Joffrey"
Yeah you need to call it once per string and per variable, it replaces all occurrences. Although you could of course build your own function on top. But if you're doing this, you most likely need a more robust solution like an actual templating framework