Scala原始字符串:每行开头有额外的制表符

3
我正在使用原始字符串,但是当我打印该字符串时,每行开头都会出现额外的制表符。
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个回答

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的作用是去除原始字符串每行开头的|字符及其之前的任何内容。

编辑:这是一个已知的Scala错误 -- 感谢extempore :)

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

希望对您有所帮助 :)

-- Flaviu Cipcigan


这也会发生在多行XML中。现在我想起来了...我认为这是一个错误。REPL没有理由添加我没有自己编写的内容。 - Daniel C. Sobral
是的,Flaviu在Scala问题上的回答非常出色,以至于我现在很少回答问题了。 - Daniel C. Sobral
@Brian:不客气 :) @Daniel:我也以为这是一个错误,但似乎它仍然存在于最近的2.8夜间构建中,并且标准库中内置了一个解决方法,即stripMargin(尽管在其他情况下stripMargin也很有用...)。你知道这个问题是否有任何错误报告吗? - Flaviu Cipcigan
@Daniel:谢谢你的点赞!Scala SO社区实际上是我接近真实世界Scala经验的途径。我正在认真考虑在我的计算物理项目中使用Scala,但在我能够说服正确的人之前,我现在所做的大部分Scala都是在SO上。不过不用担心...我的SO存在可能会受到周一开学的影响 :)。 - Flaviu Cipcigan
我肯定会需要一个智者来回答更多的Scala问题 ;) - BefittingTheorem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接