开发者

Short for String.format in Scala

开发者 https://www.devze.com 2023-04-12 05:18 出处:网络
Is there a short syntax for string interpolation in Scala? So开发者_开发技巧mething like: \"my name is %s\" < \"jhonny\"

Is there a short syntax for string interpolation in Scala? So开发者_开发技巧mething like:

"my name is %s" < "jhonny"

Instead of

"my name is %s" format "jhonny"


No, but you can add it yourself:

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

Note that you can't use <, because that would conflict with a different implicit conversion already defined in Predef.


In case you are wondering what syntax may be in the works

$ ./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

Playing some more:

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


I seem to remember Martin Odersky having been quoted with stating that string concatenation in the style presented in "Programming in Scala" is a useful approximation to interpolation. The idea is that without spaces you are only using a few extra characters per substitution. For example:

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

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

The format method provides a lot more power however. Daniel Sobral has blogged on a regex based technique too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号