3.4 字符串与多行原始字符串

Scala的字符串只不过是java.lang.String,可以按照Java的方式使用字符串。不过,Scala还为使用字符串提供了一些额外的便利。

Scala可以自动把String转换成scala.runtime.RichString——这样你就可以无缝地使用诸如capitalize()lines()reverse这样一些便捷的方法④。

④不过,这个无缝转换后的结果可能会让你大吃一惊。比如,"mom".reverse == "mom"的结果是false,因为最终比较的是RichString的实例和String的实例。不过,"mom".reverse.toString == "mom"的结果是true

在Scala里,创建多行字符串真的很容易,只要把多行字符串放在3个双引号间("""…""")即可。这是Scala对于here document,或者叫heredoc的支持。这里,我们创建了一个3行长的字符串:

ScalaForTheJavaEyes/MultiLine.scala

  1. val str = """In his famous inaugural speech, John F. Kennedy said
  2. "And so, my fellow Americans: ask not what your country can do
  3. for you-ask what you can do for your country." He then proceeded
  4. to speak to the citizens of the World..."""
  5. println(str)

输出如下:

  1. In his famous inaugural speech, John F. Kennedy said
  2. "And so, my fellow Americans: ask not what your country can do
  3. for you-ask what you can do for your country." He then proceeded
  4. to speak to the citizens of the World...

Scala允许在字符串里嵌入双引号。Scala会将三个双引号里的内容保持原样,在Scala里,称为原始字符串。实际上,Scala处理字符串有些望文生义;如果不想把代码里的缩进带到字符串里,可以用RichString的便捷方法stripMargin(),像这样:

ScalaForTheJavaEyes/MultiLine2.scala

  1. val str = """In his famous inaugural speech, John F. Kennedy said
  2. |"And so, my fellow Americans: ask not what your country can do
  3. |for you-ask what you can do for your country." He then proceeded
  4. |to speak to the citizens of the World...""".stripMargin
  5. println(str)

stripMargin()会去掉先导管道符(|)前所有的空白或控制字符。如果出现在其他地方,而不是每行的开始,就会保留管道符。如果出于某种原因,这个符号有特殊的用途,可以用stripMargin()方法的变体,接收你所选择的其他边缘(margin)字符。上面代码的输出如下:

  1. In his famous inaugural speech, John F. Kennedy said
  2. "And so, my fellow Americans: ask not what your country can do
  3. for you-ask what you can do for your country." He then proceeded
  4. to speak to the citizens of the World...

创建正则表达式时,你会发现原始字符串非常有用。键入和阅读"""\d2:\d2"""可比"\d2:\d2"容易。