Scala Raw Strings:每行开头的额外选项卡

时间:2010-01-06 14:53:49

标签: string scala

我正在使用原始字符串但是当我打印字符串时,我会在每行的开头获得额外的标签。

val rawString = """here is some text
and now im on the next line
and this is the thrid line, and we're done"""

println(rawString)

此输出

here is some text
    and now im on the next line
    and this is the thrid line, and we're done

我尝试过设置不同的行结尾,但没有效果。 我正在使用jEdit作为我的编辑器在Mac(OS X tiger)上工作。当我在scala解释器中运行脚本或将输出写入文件时,我得到相同的结果。

有谁知道这里发生了什么?

1 个答案:

答案 0 :(得分:11)

此问题是由于您在解释器中使用多行原始字符串这一事实。您可以看到额外空格的宽度正好是scala>提示符的大小或管道的大小+解释器在您创建新行时添加的空格以便保持排列。

scala> val rawString = """here is some text          // new line
     | and now im on the next line                   // scala adds spaces 
     | and this is the thrid line, and we're done""" // to line things up
// note that the comments would be included in a raw string...
// they are here just to explain what happens

rawString: java.lang.String =
here is some text
       and now im on the next line
       and this is the thrid line, and we're done

// you can see that the string produced by the interpreter
// is aligned with the previous spacing, but without the pipe

如果您在Scala脚本中编写代码并将其作为scala filename.scala运行,则无法获得额外的选项卡。

或者,您可以在解释器中使用以下构造:

val rawString = """|here is some text
                   |and now im on the next line
                   |and this is the thrid line, and we're done""".stripMargin

println(rawString)

stripMargin做的是在原始字符串的每一行的开头处包括|字符之前的任何内容。

编辑:这是known Scala bug - 感谢extempore:)

更新:已在trunk中修复。再次感谢extempore :)。

希望有所帮助:)

- Flaviu Cipcigan