Scala interpolate String from variable

拟墨画扇 提交于 2020-05-16 05:22:07

问题


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 name with value "Bill"
  • There is a String variable greeting which contains characters ['M','y',' ','n','a','m','e',' ','i','s',' ','$','{','n','a','m','e','}'] (completely unrelated to the variable name, 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 from greeting. Since

    val y = "whatever"
    val x = s"${y}"
    

    must always result in variable x having the same content as variable y, the variable result ends up having the same value as greeting, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!