【发布时间】:2011-09-08 09:05:56
【问题描述】:
是否有默认的(在 SDK 中)scala 支持字符串模板?示例:“$firstName $lastName”(命名为未编号的参数)甚至是 for/if 之类的构造。如果没有这样的默认引擎,那么最好的 scala 库是什么?
【问题讨论】:
-
更新:命名参数是首选。
标签: templates scala core template-engine
是否有默认的(在 SDK 中)scala 支持字符串模板?示例:“$firstName $lastName”(命名为未编号的参数)甚至是 for/if 之类的构造。如果没有这样的默认引擎,那么最好的 scala 库是什么?
【问题讨论】:
标签: templates scala core template-engine
在 Scala 2.10 及更高版本中,您可以使用string interpolation
val name = "James"
println(s"Hello, $name") // Hello, James
val height = 1.9d
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall
【讨论】:
这个编译器插件提供了一段时间的字符串插值:
http://jrudolph.github.com/scala-enhanced-strings/Overview.scala.html
最近,该功能似乎正在进入 scala 主干:https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/run/stringInterpolation.scala——它产生了一些有趣的可能性:https://gist.github.com/a69d8ffbfe9f42e65fbf(不确定这些是否可以通过插件实现;我对此表示怀疑)。
【讨论】:
补充Kim'sanswer,注意Java的Formatter接受位置参数。例如:
"%2$s %1$s".format(firstName, lastName)
另外,还有Enhanced Strings 插件,它允许在字符串上嵌入任意表达式。例如:
@EnhanceStrings // enhance strings in this scope
trait Example1 {
val x = 5
val str = "Inner string arithmetics: #{{ x * x + 12 }}"
}
有关更多答案,另请参阅此question,因为这确实是非常接近的副本。
【讨论】:
如果你想要一个模板引擎,我建议你看看scalate。如果您只需要字符串插值,"%s %s".format(firstName, lastName) 是您的朋友。
【讨论】: