代码之家  ›  专栏  ›  技术社区  ›  BefittingTheorem

scala原始字符串:每行开头的额外选项卡

  •  3
  • BefittingTheorem  · 技术社区  · 15 年前

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

    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 回复  |  直到 15 年前
        1
  •  11
  •   Community CDub    7 年前

    这个问题是由于您在解释器中使用了多行原始字符串。您可以看到,额外空间的宽度正好是 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 . 谢谢 即席的 再次:)

    希望有帮助:)

    --弗拉维厄·西皮根