Why is there no string interpolation in Scala?

て烟熏妆下的殇ゞ 提交于 2019-11-29 13:18:30
retronym

The proposed solution is to omit spaces when using +.

"a="+a+", b="+b

It has been suggested that a Swiss keyboard layout makes this very natural to type, so the creators of Scala don't feel enough pain to justify complicating the langauge in this direction :)

String interpolation is in Scala 2.10. See the SIP.

If you're using an earlier Scala version, there's also the ScalaEnhancedStrings compiler plugin.

It was deemed that the extra compiler complexity that would result from it was not worth the gains to be had on one hand, and, on the other hand, that its absence would not be overly burdensome.

Matt R

I gather the feeling is that String interpolation is unnecessary, because it's not much more concise than concatenation:

val str2 = "Hello, ${str1}!"
val str2 = "Hello, "+str1+"!"

Arguing that the "+" operator on Strings should be formatted without a space, Martin Odersky says,

With the new convention, the need for string substitution (often put forward on Scala lists) all but disappears. Compare:

"test results: ${result1}, ${result2}"

with the first version above. You have saved one character per substitution, hardly worth a new syntax convention. In other words, Scala's string substitution syntax is written

"+...+"

instead of

${...}

or some other similar proposal. On the other hand, if you insist on spaces around the +, the story becomes much less convincing.

Incidentally, see the blog post, "String Interpolation in Scala" where it's emulated using reflection.

Starting in Scala 2.10.0, Scala does support String Interpolation

Example:

val name = "James"
println(s"Hello, $name")  // Hello, James

String interpolation is currently being added to Scala in the trunk, see this commit by Martin, so it will probably be available in Scala 2.10. See also the first test case for an example: https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/run/stringInterpolation.scala

Scala does have a similar feature for XML:

val x = doSomeCrazyCalculation
val xml = <foo>{x}</foo>
eptx

Consider that the XML literal is evaluated only once. See Scala multiline string placeholder for question variant dealing with multi-line strings.

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