[英]Short for String.format in Scala
Is there a short syntax for string interpolation in Scala? Scala中的字符串插值有一个简短的语法吗? Something 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. 请注意,您不能使用
<
,因为这会与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. 我似乎记得Martin Odersky被引用时声称在“Scala编程”中提供的样式中的字符串连接是插值的有用近似。 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.
Daniel Sobral也在博客上发表了一种基于正则表达式的技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.