Is there a way to interpolate the `$variable` in a...
# getting-started
z
Is there a way to interpolate the
$variable
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
No. Interpolation is done at compile time.
j
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"
See it in action in the playground
z
yeah, the only issue here is
replace
has to be called many times.
j
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