问题
String interpolation works fine in this case:
val name = "Bill"
val result = s"My Name is ${name}"
When I introduce it to the variable it didn't get interpolated value:
val name = "Bill"
val greeting = "My Name is ${name}"
val result = s"${greeting}"
Direct wrapping of greeting is not appropriate solution, I must handle greeting like a plain String.
回答1:
String interpolation in Scala does not compose in the way you expect.
The issue for this has been debated. Folks want it, but folks don't always get what they want.
You could imagine writing some macros that work in concert. One defines a function taking a string, the other knows how to interpolate it by invoking it with the correctly named value in scope.
Also worth adding that interpolation is not a generic runtime templating mechanism. For example, you can't read strings from a file of the form "$greeting" and run interpolation substitutions on it.
回答2:
- There is an unused variable
namewith value"Bill" - There is a
Stringvariablegreetingwhich contains characters['M','y',' ','n','a','m','e',' ','i','s',' ','$','{','n','a','m','e','}'](completely unrelated to the variablename, the four characters'n','a','m','e'have no possibility of getting anywhere near compiler's symbol table, which is good). There is a variable
result, whose value is computed by string interpolation fromgreeting. Sinceval y = "whatever" val x = s"${y}"must always result in variable
xhaving the same content as variabley, the variableresultends up having the same value asgreeting, namely"My Name is ${name}".
If the compiler tried to execute every substring that looks somewhat like Scala code, this would result in total chaos, because every time something can leak from the realm of String-data into the realm of executable code, it makes the code vulnerable for all kind of injection exploits.
来源:https://stackoverflow.com/questions/50655112/scala-interpolate-string-from-variable