2011-10-10 84 views
7

Scala中有字符串插值的簡短語法嗎?喜歡的東西:Scala中String.format的縮寫

"my name is %s" < "jhonny" 

而不是

"my name is %s" format "jhonny" 
+1

新詞彙字:字符串插值(我瞭解到一個最近自己)。 –

+0

哦,謝謝。我會將其添加到問題中。 –

+1

是的,我也發現這個:http://stackoverflow.com/questions/2481459/why-is-there-no-string-interpolation-in-scala –

回答

9

沒有,但你可以自己添加它:你不能使用<,因爲這將有衝突

scala> implicit def betterString(s:String) = new { def %(as:Any*)=s.format(as:_*) } 
betterString: (s: String)java.lang.Object{def %(as: Any*): String} 

scala> "%s" % "hello" 
res3: String = hello 

注Predef中已經定義了不同的隱式轉換。

3

我似乎記得馬丁奧德斯基曾經引用過,在「斯卡拉編程」中提出的風格中的字符串連接是一種有用的內插近似。這個想法是,如果沒有空格,每個替換隻能使用一些額外的字符。例如:

val x  = "Mork" 
val y  = "Ork" 

val intro = "my name is"+x+", I come from "+y 

然而,format方法提供了更多的功能。 Daniel Sobral也在regex based技術上發表過博文。

+0

串聯的問題是,有時你會失去整個字符串的'視圖'。例如「%s://%s」格式(協議,主機)對我來說看起來更清潔。 –

4

如果你想知道什麼語法可能會在作品

$ ./scala -nobootcp -Xexperimental 
Welcome to Scala version 2.10.0.r25815-b20111011020241 

scala> val s = "jhonny" 
s: String = jhonny 

scala> "my name is \{ s }" 
res0: String = my name is jhonny 

打一些:你

scala> "those things \{ "ne\{ "ts".reverse }" }" 
res9: String = those things nest 

scala> println("Hello \{ readLine("Who am I speaking to?") }") 
Who am I speaking to?[typed Bozo here]Hello Bozo