为什么Scala 中没有字符串插值?
这不仅仅是一句闲话……我想知道是否有人知道 Scala 不支持类似于 Groovy 和其他“语法上更好的 Java”的插值是否有实际的设计原因?
例如
var str1 = "World"; var str2 = "Hello, ${str1}";
This is not just an idle quip... I wonder if anybody knows if there's an actual design reason why Scala does not support interpolation similar to Groovy and other "syntactically better Javas"?
e.g.
var str1 = "World"; var str2 = "Hello, ${str1}";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
字符串插值是在 Scala 2.10 中。请参阅 SIP。
如果您使用的是早期的 Scala 版本,还有 ScalaEnhancedStrings 编译器插件< /a>.
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.
建议的解决方案是在使用
+
时省略空格。它已经建议瑞士键盘布局使输入变得非常自然,因此 Scala 的创建者不会感到足够的痛苦来证明在这个方向上使语言复杂化是合理的:)
The proposed solution is to omit spaces when using
+
.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 :)
从 Scala 2.10.0 开始,Scala 支持字符串插值
示例:
Starting in Scala 2.10.0, Scala does support String Interpolation
Example:
人们认为,一方面,由此带来的额外的编译器复杂性不值得获得,另一方面,它的缺失也不会造成太大的负担。
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.
我感觉字符串插值是不必要的,因为它并不比连接简洁多少:
争论字符串上的“+”运算符应该格式化而没有空格, Martin Odersky 说,
顺便说一下,请参阅博客文章“字符串插值在 Scala 中,它是使用反射来模拟的。
I gather the feeling is that String interpolation is unnecessary, because it's not much more concise than concatenation:
Arguing that the "+" operator on Strings should be formatted without a space, Martin Odersky says,
Incidentally, see the blog post, "String Interpolation in Scala" where it's emulated using reflection.
字符串插值目前正在主干中添加到 Scala,请参阅 Martin 的 此提交,因此它将可能会在 Scala 2.10 中提供。另请参阅第一个测试用例的示例: https:// lampvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/run/stringInterpolation.scala
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 对于 XML 确实有类似的功能:
Scala does have a similar feature for XML:
考虑一下 XML 文字仅被计算一次。有关处理多行字符串的问题变体,请参阅 Scala 多行字符串占位符。
Consider that the XML literal is evaluated only once. See Scala multiline string placeholder for question variant dealing with multi-line strings.