2011-10-27 79 views
15

我想问一下在Scala中是否有任何类型的字符串插值。我已经搜索了这个主题,但'直到现在我发现没有字符串插值。是否有计划在下一个版本中实施?斯卡拉字符串插值?

谢谢!

UPDATE

字符串插值要在斯卡拉2.10,你可以尝试一下,因为斯卡拉2.10.RC1是出(20/10/2012)。您可以查看这个scala 2.11的SIP,其中指出模式匹配器中的插入字符串将是有效的语法。随着新的串插,你可以做这样的事情:

val age = 28 
val name = "Gerry" 

s"My name is $name and I am $age years old" 
res0: String = My name is Gerry and I am 28 years old 

但尝试了documentation上的所有可用此刻的插值。请注意,您可以定义自己的插补器!有关更多信息,请尝试this link

+0

http://docs.scala-lang.org/sips/index.html – Debilski

+2

为了完整性,对于不具有那些参数是'“(” +值+“)”'只有一个字符长(#{value})“' –

+1

[为什么Scala中没有字符串插值?](http:// stackoverflow。com/questions/2481459/why-is-there-no-string-interpolation-in-scala) –

回答

22

它不在(发布)的scala库中。但对于这项新增功能的SIP(斯卡拉改进过程):

http://docs.scala-lang.org/sips/pending/string-interpolation.html

+3

它也已经在trunk中(作为实验性功能):https://lampsvn.epfl.ch/trac/scala/changeset/ 25812/ – tenshi

+0

@tenshi谢谢!如果我有时间的话,我要检查是否有躯干。 –

14

你可以做到这一点C风格:

"Interpolate my %s here" format List(1,2,3) 

//String = Interpolate my List(1, 2, 3) here 

List(1,2,3) formatted "Interpolate my %s here" 

你可以在toString上使用这些东西(即任何东西)

case class Foo(n: Int) 
Foo(42) formatted "Here is a %s !!!!" 
//String = Here is a Foo(42) !!!! 

尽管前者在单个字符串中启用多个插值(因为它可能需要多个参数)方面更灵活。

7

我使用xml上阶破解2.9

val age = 28 
val name = "Gerry" 

<a>My name is {name} and I am {age} years old</a>.text 
res0: String = My name is Gerry and I am 28 years old 
+2

这可能是旧的,但它是一个很好的黑客! – javadba

0

这天(12月到2016年,斯卡拉2.12,五几年后),您可以编写自己的字符串插值。
co.ntextu.al

语境是一个小的Scala库,它允许你定义自己的字符串插值前缀字符串文字像uri"https://google.com"它决定他们应该如何进行评估,在运行时在编译时,而只写非常普通的用户代码:无宏!

例如,contextual/examples/email.scala允许check at compile time the validity of an email address

import contextual.examples.email._ 
email"""[email protected]""" 

import contextual.examples.email._ 
email"""[email protected]"""